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

More Related Content

Similar to Excel-Quick-Reference-Guide.pdf

Data Structures- Part1 overview and review
Data Structures- Part1 overview and reviewData Structures- Part1 overview and review
Data Structures- Part1 overview and review
Abdullah Al-hazmy
 
ms-excel.pptx
ms-excel.pptxms-excel.pptx
ms-excel.pptx
Moises Tenyosa
 
Kofi Nyanteng Introduction excel modelling
Kofi Nyanteng Introduction excel modellingKofi Nyanteng Introduction excel modelling
Kofi Nyanteng Introduction excel modelling
Kofi Kyeremateng Nyanteng
 
Kofi Nyanteng Introduction excel modelling
Kofi Nyanteng Introduction excel modellingKofi Nyanteng Introduction excel modelling
Kofi Nyanteng Introduction excel modelling
Kofi Kyeremateng Nyanteng
 
Introduction to Basic Spreadsheets
Introduction to Basic SpreadsheetsIntroduction to Basic Spreadsheets
Introduction to Basic Spreadsheets
Kingston Tagoe
 
Use of MathType software with MSWord
Use of MathType software with MSWordUse of MathType software with MSWord
Use of MathType software with MSWord
Madurai
 
Introduction to programming - class 3
Introduction to programming - class 3Introduction to programming - class 3
Introduction to programming - class 3
Paul Brebner
 
Introduction to Excel
Introduction to ExcelIntroduction to Excel
Introduction to ExcelNajma Alam
 
excell.pdf
excell.pdfexcell.pdf
excell.pdf
ssuser8f8817
 
Csci101 lect03 algorithms_i
Csci101 lect03 algorithms_iCsci101 lect03 algorithms_i
Csci101 lect03 algorithms_i
Elsayed Hemayed
 
Python
PythonPython
Software fundamentals
Software fundamentalsSoftware fundamentals
Software fundamentals
Susan Winters
 
Functions, Types, Programs and Effects
Functions, Types, Programs and EffectsFunctions, Types, Programs and Effects
Functions, Types, Programs and Effects
Raymond Roestenburg
 
Crosstab query techniques
Crosstab query techniquesCrosstab query techniques
Crosstab query techniquesaabaap
 
Introduction to excel for survival
Introduction to excel for survivalIntroduction to excel for survival
Introduction to excel for survival
Jacob Mazalale
 
Data Transformation
Data TransformationData Transformation
Data Transformation
ArmanArafatAnik
 
Computation Chapter 4
Computation Chapter 4Computation Chapter 4
Computation Chapter 4
Inocentshuja Ahmad
 
9 - Advanced Functions in MS Excel.pptx
9 - Advanced Functions in MS Excel.pptx9 - Advanced Functions in MS Excel.pptx
9 - Advanced Functions in MS Excel.pptx
SheryldeVilla2
 
Microsoft Excel- basics
Microsoft Excel-  basicsMicrosoft Excel-  basics
Microsoft Excel- basics
jeshin jose
 

Similar to Excel-Quick-Reference-Guide.pdf (20)

Data Structures- Part1 overview and review
Data Structures- Part1 overview and reviewData Structures- Part1 overview and review
Data Structures- Part1 overview and review
 
ms-excel.pptx
ms-excel.pptxms-excel.pptx
ms-excel.pptx
 
003.query
003.query003.query
003.query
 
Kofi Nyanteng Introduction excel modelling
Kofi Nyanteng Introduction excel modellingKofi Nyanteng Introduction excel modelling
Kofi Nyanteng Introduction excel modelling
 
Kofi Nyanteng Introduction excel modelling
Kofi Nyanteng Introduction excel modellingKofi Nyanteng Introduction excel modelling
Kofi Nyanteng Introduction excel modelling
 
Introduction to Basic Spreadsheets
Introduction to Basic SpreadsheetsIntroduction to Basic Spreadsheets
Introduction to Basic Spreadsheets
 
Use of MathType software with MSWord
Use of MathType software with MSWordUse of MathType software with MSWord
Use of MathType software with MSWord
 
Introduction to programming - class 3
Introduction to programming - class 3Introduction to programming - class 3
Introduction to programming - class 3
 
Introduction to Excel
Introduction to ExcelIntroduction to Excel
Introduction to Excel
 
excell.pdf
excell.pdfexcell.pdf
excell.pdf
 
Csci101 lect03 algorithms_i
Csci101 lect03 algorithms_iCsci101 lect03 algorithms_i
Csci101 lect03 algorithms_i
 
Python
PythonPython
Python
 
Software fundamentals
Software fundamentalsSoftware fundamentals
Software fundamentals
 
Functions, Types, Programs and Effects
Functions, Types, Programs and EffectsFunctions, Types, Programs and Effects
Functions, Types, Programs and Effects
 
Crosstab query techniques
Crosstab query techniquesCrosstab query techniques
Crosstab query techniques
 
Introduction to excel for survival
Introduction to excel for survivalIntroduction to excel for survival
Introduction to excel for survival
 
Data Transformation
Data TransformationData Transformation
Data Transformation
 
Computation Chapter 4
Computation Chapter 4Computation Chapter 4
Computation Chapter 4
 
9 - Advanced Functions in MS Excel.pptx
9 - Advanced Functions in MS Excel.pptx9 - Advanced Functions in MS Excel.pptx
9 - Advanced Functions in MS Excel.pptx
 
Microsoft Excel- basics
Microsoft Excel-  basicsMicrosoft Excel-  basics
Microsoft Excel- basics
 

Recently uploaded

Atelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissancesAtelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Neo4j
 
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
Alina Yurenko
 
GraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph TechnologyGraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph Technology
Neo4j
 
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOMLORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
lorraineandreiamcidl
 
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket ManagementUtilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
Globus
 
Introduction to Pygame (Lecture 7 Python Game Development)
Introduction to Pygame (Lecture 7 Python Game Development)Introduction to Pygame (Lecture 7 Python Game Development)
Introduction to Pygame (Lecture 7 Python Game Development)
abdulrafaychaudhry
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
Google
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Globus
 
Nidhi Software Price. Fact , Costs, Tips
Nidhi Software Price. Fact , Costs, TipsNidhi Software Price. Fact , Costs, Tips
Nidhi Software Price. Fact , Costs, Tips
vrstrong314
 
A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
Philip Schwarz
 
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI AppAI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
Google
 
Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"
Donna Lenk
 
E-commerce Application Development Company.pdf
E-commerce Application Development Company.pdfE-commerce Application Development Company.pdf
E-commerce Application Development Company.pdf
Hornet Dynamics
 
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdfAutomated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
timtebeek1
 
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Łukasz Chruściel
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus
 
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
XfilesPro
 
Game Development with Unity3D (Game Development lecture 3)
Game Development  with Unity3D (Game Development lecture 3)Game Development  with Unity3D (Game Development lecture 3)
Game Development with Unity3D (Game Development lecture 3)
abdulrafaychaudhry
 
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdfVitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke
 

Recently uploaded (20)

Atelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissancesAtelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissances
 
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
 
GraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph TechnologyGraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph Technology
 
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOMLORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
 
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket ManagementUtilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
 
Introduction to Pygame (Lecture 7 Python Game Development)
Introduction to Pygame (Lecture 7 Python Game Development)Introduction to Pygame (Lecture 7 Python Game Development)
Introduction to Pygame (Lecture 7 Python Game Development)
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
 
Nidhi Software Price. Fact , Costs, Tips
Nidhi Software Price. Fact , Costs, TipsNidhi Software Price. Fact , Costs, Tips
Nidhi Software Price. Fact , Costs, Tips
 
A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
 
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI AppAI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
 
Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"
 
E-commerce Application Development Company.pdf
E-commerce Application Development Company.pdfE-commerce Application Development Company.pdf
E-commerce Application Development Company.pdf
 
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdfAutomated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
 
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
 
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
 
Game Development with Unity3D (Game Development lecture 3)
Game Development  with Unity3D (Game Development lecture 3)Game Development  with Unity3D (Game Development lecture 3)
Game Development with Unity3D (Game Development lecture 3)
 
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdfVitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdf
 

Excel-Quick-Reference-Guide.pdf

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