Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

Excel Macro VBA Quick Reference Math/Financial/Formatting Functions Turn a String into a Value: Value(string)

Math - Abs(num), Exp(num), Int(num), Rnd(num), Randomize, Single Characters: Char(65) = “A” – Uses the Ascii characters
Guide Round(num,digits), Sqr(num)
Find a string within another string: Instr([start],[string
Website: http://everydayvba.com Financial - FV(rate, nper, pmt[, pv[, type]]), NPV(rate, values()), PV(rate, searching],[searching for], [Optional Compare Method])
Facebook: everydayvba nper, pmt[, fv[, type]]), Pmt(rate, nper, pv[, fv[, type]]), PPmt(rate, per,
YouTube: everydayvba nper, pv[, fv[, type]]) Split a string based on a delimiter (returns data in array): Split([string],
[delimiter], [Optional Limit],[Optional Compare])
Format - Format(“number, string, or date”, “format” )
Color Coding in the Coding Window Number Format Format(“num”, “Pos Num”:”Neg Num”:”Zero”) Conditional Statements
Black=Regular Code Blue=Keywords Green=Comments Red=Errors 0 – Leading Digit # – No Leading or Trailing Zero Conditionally executes a statements, depending on the value of the
‘ (single quote) to leave a comment in the code e+ or e- – Exponential % – Percentages condition. If it is true the group of statements will be processed
Numbers have three formatting Options Positive, Negative, and Zero
Quick Keys If [condition 1] Then Select Case [Variable]
Alt + F11 Open Visual Basic Editor F5 Run Code String Format [statements] Case [condition]
F8 Step into (one line at a time) F9 Add a Break point @ – Character or Space & – Character or Nothing ElseIf [condition 2] Then [statements]
! – Cut from the left [statements] Case [condition 2]
F2 Object browser F4 Properties Window
Else [statements]
Shift + F8 Step Over Ctrl + Break Break Loop Date Format [statements] Case Else
Ctrl + J List Property Methods Alt + G Immediate Window d, m, y, h, n, s – Day Month, Year, Hours, Min, Sec w/o leading 0 “5” End If [statements]
dd, mm, yy, hh, nn, ss – – Day Month, Year, Hours, Min, Sec “05” End Select
ddd, mmm – Day “Sun”, Month “Jun”
Operators – Mathematical and Logical
dddd , mmmm– Day “Sunday”, Month “June” Message Box Input Box
Numbers: + (plus) – (minus) * (times) / (divide) ^ (exponent) ww – Week Number
MsgBox(“Prompt”, [button types]+[icons (optional)], “Title”, [helpfile],
y – Day of Year yy – 2 Digit Year “16” yyyy – 4 digit Year “2016”
Strings: & (string concatenate) [context])
AM/PM or am/pm – Show AM/am PM/pm 12 hour clock
Button Types (Constant Integer)
Comparisons: = (equals) < (less than) <= (less than or equal) > (greater vbOKOnly (0) vbOKCancel (1) vbAbortRetryIgnore(2)
Date Time Functions – (Class = Date Time) vbYesNoCancel (3) vbYesNo (4) vbRetryCancel (5)
than) >= (greater than or equal)
In Excel and Most Programing Languages one date is equal to 1 and today Icons
Conditional Statement: Something that is True or False is the number of days since 1/1/1900. Where fractions of 1 represent vbCritical (16) vbQuestion (32) vbExclamation (48)
minutes and seconds. vbInformation (64)
Boolean (for conditional statements): AND, OR, NOT
Now() - Current date and time Date() - Current date Button Constants (Constant Integer)
Time() - Current time Timer() - Sec since midnight vbOK (1) vbCancel (2) vbAbort(3)
Procedure and Functions (the Start and end of a Macro Procedure)
Date = Var - Sets current date Time = Var - Sets current time vbRetry (4) vbIgnore (5) vbYes (6)
Procedure Types: Public: Visible to ALL modules (this is the default Day(#11/05/2016#) = 5 Month(#11/05/2016#) = 11 vbNo (7)
procedure type), Private: Visible to this Module Only Year(#11/05/2016#) = 2016 Weekday(#11/05/2016#) = 7
Hour(.5) = 12 Minute(.501) = 1 InputBox(prompt[, title] [, default] [, xpos] [, ypos] [, helpfile, context])
Syntax [procedure type] Second(.501) = 26 Ibox = InputBox(“Message”,” Title”)
Sub [Procedure Name] ([Optional])
Ibox = User response from the Input box as a String Variable
[Code or statements] DateSerial(2020, 11, 05) = #11/05/2020# NOTE: if “Cancel” is clicked ibox will be “” or [blank]
End Sub TimeSerial(8, 0, 0) = 0.25 or 8:00:00
Appplication Inputbox has some advantages specifically allows the user
Function [Function Name]([variable1],[variable2])
String Functions to select the preferred data type
[Code or statements]
Syntax: [variable] = Left(“This is a string”,4) | [variable] = “This” Ibox = Application.InputBox(Prompt, Title, Default, Left, Top, HelpFile,
End Function
HelpContextID, Type)
Strip characters from a string: Left(string, length), Right(string, length), Input Types
Data Types/Declaring Variables 0 - A formula 1 - A number
Mid(start, string, [length]) – used for the finding the middle of a string
Declaring Variable Syntax: Dim [variable name] As [variable type] 2 - Text (a string) 4 - A logical value (True or False)
Declaration Types: Dim = Procedural variable, Static = Procedure variable Change String Case: Ucase(string) – Makes string uppercase. 8 - A cell reference, as a Range object
that retains value, and Public = Globally used variable LCase(string) – Makes string lowercase 16 - An error value, such as #N/A
64 - An array of values
Variable Types: Integer (whole numbers), Long (Larger Whole Numbers), Find the length of the sting or number of characters: Len(String)
Double (numbers with decimals), Boolean (True or False), String (Text),
Variant (Default Variable Excel chooses the data Type), Date (Date) “I am always doing that which I cannot do, in order
Get rid of spaces: LTrim(String) – Remove spaces on the Left,
Rtrim(String) – Remove spaces on Right that I may learn how to do it.”
Object Types: Workbook, Worksheet, Range Trim(String) – Remove spaces on left and right of string
― Pablo Picasso
Iterations or Loops AutoFilter EnableAutoFilter Rows Activate Change Click
Loops repeat a block of statements while its conditions are true, a Cells Hyperlinks Shapes DblClick Enter Exit
specified number of times is completed, or through each element of a CircularReference Name Sort Key Down KeyPress KeyUp
collection (like each sheet in all the sheets in a workbook) Columns Names StandardHeight MouseDown MouseMove MouseUp
Comments PageSetup StandardWidth Deactivate Initialize GotFocus
Do While will repeat until the condition is False Count Parent Visible Load Scroll Terminate
Do Until will repeat until the condition is True DisplayPageBreaks Range
Worksheet – Methods (Class = Sheet1) Arrays
Do While [Condition is True] Do Until [Condition is False] Activate Paste Protect An array is a group of variables and you can refer to a specific variable
[statements] [statements] Add PasteSpecial ResetAllPageBreaks (element) of an array by using the array name and the index number
Exit Do [optional] Exit Do [optional] Calculate PivotTableWizard SaveAs Declaring An Array: Dim ArrayName(Start to End) or Static Array
[statements] [statements] Copy PrintOut Select Dim ArrayName() Dynamic Array
Loop Loop Delete PrintPreview Unprotect Example: Dim Oarray(1 to 3)
Move Assigning Data to the Array using Index | Assigning Array(index) to
For x = 100 to 1 Step -1 x is reduced by one until it reaches 1 Worksheet - Events Variable (See Below)
For Each ws in Worksheets will go through all the sheets every loop ws Activate BeforeRightClick Change Oarray(1) = “This” x = Oarray(1) x = “This”
will be assigned a new sheet BeforeDoubleClick Calculate Oarray(2) = “Is” x = Oarray(2) x = “Is”
Oarray(3) = “An Array” x = Oarray(3) x = “An Array”
For [counter] = [start] to [end] For Each [element] in [group] Workbooks – Properties (Class = ThisWorkbook)
[statements] [statements] ActiveChart HasPassword Sheets Redim Oarray(1 to 10) If an array size is going to change Redim must be
Exit For [optional] Exit For [optional] ActiveSheet Name ThisWorkbook used - This will delete all the data from the array
[statements] [statements] Charts Names User Redim Preserve Oarray(1 to 15) – Preserve will keep the data in the array
Next Next FileFormat Path Worksheets AND resize the array
Range and Cell - Properties FullName ReadOnly Ubound and Lbound
AddIndent Height Rows Workbooks – Methods Ubound(Oarray) = 15 Returns the highest available subscript for the
Address Hidden Text Activate PrintPreview SaveAs indicated dimension of an array
AllowEdit Hyperlinks Validation Close Protect Unprotect Lbound(Oarray) = 1 Returns the lowest available subscript for the
Borders IndentLevel Value PrintOut Save indicated dimension of an array
Cells Interior VerticalAlignment Workbooks – Events Multi-Dimensional Array
Characters Item Width Activate NewChart SheetChange LBound(Oarray) first index
Column Locked Worksheet AfterSave NewSheet WindowActivate LBound(Oarray, 2 ) Lower bound for second index for a two dimensional
Columns MergeArea WrapText BeforeClose Open WindowDeactivate array
ColumnWidth MergeCells Resize BeforePrint SheetCalculate WindowResize UBound(Oarray) Upper bound for first index
Comment Name Row BeforeSave UBound(Oarray, 3) Upper bound for third index
Count NumberFormat RowHeight
CurrentRegion Offset Rows Forms Erase Oarray Empties the Array’s data
End Orientation Text Start or Initialize form: Load [form name]
EntireColumn OutlineLevel UseStandardHeight From Range to an Array (NOTE: It will be a two dimensional Array)
EntireRow PageBreak UseStandardWidth Display a User Form or make is visible: [form name].Show Dim Oarray as Variant
Font Parent Validation Hide the Form or make invisible: [form name].Hide Oarray = Range(“A1:C10”) Creates and Array Oarray(1 to 10, 1 to 3)
Formula Resize Value
FormulaR1C1 Row VerticalAlignment Close or quit form: Unload [form me] Oarray = Range(“A1”).CurrentRegion This is a powerful
HasFormula RowHeight Width Unload a Form from within the Userform Private Subs: Unload Me
Range and Cell - Methods From an Array to a Range (This is like pasting the array to the range)
Activate ClearHyperlinks Justify Form Controls Range(“A1:C10”) = Oarray This is also powerful. Keep in mind the array
AdvancedFilter Copy Merge Label Text Box Combo Box will need to be two dimensional Oarray(1 to 10, 1 to 3)
AddComment Cut PasteSpecial List Box Check Box Radio Button
ApplyNames Delete PrintOut Toggle Button Frame Button Split Function Break out a string into a an Array
AutoFill FillDown PrintPreview Multi Page Scroll Bar Spin Button Split(text_string, delimiter, [limit], [compare])
AutoFilter FillLeft RemoveDuplicates Image RefEdit Oarray = Split(“This is Text”, “ “)
AutoFit FillRight RemoveSubtotal Creates Oarray(0 to 2) with the data below
Form Events
BorderAround FillUp Replace Oarray(0) = “This” Oarray(1) = “is” Oarray(2) = “Text”
Syntax Private Sub [object name]_[event]() End Sub
Calculate Find Select
Clear FindNext Sort
The First Code that runs when Load or .Show is executed
ClearComments FindPrevious Subtotal “First, solve the problem. Then, write the code.”
Private Sub UserForm_Initialize()
ClearContents Insert TextToColumns
[statements]
ClearFormats InsertIndent UnMerge
End Sub ― John Johnson
Worksheet - Properties

You might also like