ExcelVBA Reference Guide
ExcelVBA Reference Guide
ExcelVBA Reference Guide
Excel objects
Range/Selection objects This site is used in conjunction with my classroom instructor lead teaching (for my students
attending an Excel VBA course) and is intended as a reference guide only. But if you have
Object hierarchy attended or taught Excel VBA yourself, this will help you too.
Object browser
Chart objects
You will start by learning to record, edit and manage macros in Excel capturing the VBA code
Pivot Table objects automatically giving you the confidence and basic knowledge to the VBA code language itself.
Formulas
Visual Basic Functions
Creating Add-Ins
Variables & constants
Object variables
Arrays
Collections
Message Box
VBA Input Box
Excel Input Box
Making decisions (If)
Making decisions (Case)
Looping (Do...Loop)
Looping (For...Loop)
With...End With blocks
User defined functions At some point you will want to get down to learning about the power of VBA using Excel as the
Event handling environment tool to test the code. This will introduce you to the programming conventions, concepts
and techniques that simply go beyond the scope of the Excel Macro Recorder tool.
Error handling
Debugging
Creating User Forms
DAO/ADO Objects
Input/Output Files
Other links
There is a lot more VBA code that can not be recorded which include logic testing, iteration,
interactive macros, creating functions and assigning variables.
I will gently ease you into learning VBA code smoothing out the steep learning curve as much as
possible.
Want to teach yourself Access? Free online guide at About Access Databases
All trademarks are copyrighted by their respective owners. Please read our terms of use and privacy policy.
Back to Excel Homepage Excel VBA - Reference Guide
Tip: Alt + F11 function keys switches
Other links
Activecell.Select
In plain English, this means, click on the active cell.
ActiveCell.FormulaR1C1 = ABC Ltd
In plain English, this means enter the text ABC Ltd into the active cell.
ActiveCell.Offset(1,0).Range(A1).Select
In plain English, this means, select the cell one row down, but stay in the same column.
OffSet (Keyword)
Offset is a command used in relative macros, which allows you to select a particular cell in relation to
the active cell.
Offset(-1,0)
Move one row up, but stay in the same column.
Offset(0,1)
Stay in the same row, but move one column to the right.
Offset(1,0)
Move one row down, but stay in the same column.
Offset(0,-1)
Stay in the same row, but move one column to the left.
Unnecessary Code
Want to teach yourself Access? Free online guide at About Access Databases
All trademarks are copyrighted by their respective owners. Please read our terms of use and privacy policy.
Back to Excel Homepage Excel VBA - Reference Guide
Tip: Alt + F8 function keys displays
Menu
Most users will automatically run a macro from either button on the Quick Access toolbar (known as
VBA Keywords: CommandBars,
Recording macros Toolbars on previous versions) or via the conventional Macro dialog box.
Worksheet_Change (event),
Looking at the code Workbook_Open (event),
Workbook_Close (event).
Ways of running macros The following is a list of ways to run a macro:
Where macros are stored
Reasons to write macros 1. The Macro dialog box.
Writing macros Version 2003 (or earlier) - Click on the Tools menu, select Macro and choose Macros.
Procedure types Version 2007 (or later) - From the Developer tab, click the Macro icon.
Visual Basic editor (VBE)
Rules & conventions Or the shortcut key to all versions is Alt + F8.
Excel objects
Range/Selection objects Select the Macro you wish to run and click on the Run button.
Object hierarchy
Object browser 2. Using a shortcut key as assigned, i.e. Ctrl + e.
Chart objects
Pivot Table objects 3. From a Button on the worksheet.
Formulas
Visual Basic Functions 4. From an icon Button on the Quick Access toolbar.
Creating Add-Ins Previous versions uses Toolbars.
Variables & constants
Object variables 5. From the Ribbon Bar (though requires some XML knowledge).
Arrays Previous versions uses a menu item from the menu bar.
Collections
Message Box 6. From another type of object, e.g. Chart or Graphic image.
VBA Input Box
Excel Input Box 7. From a Control drawn on the worksheet, e.g. Combo Box.
Making decisions (If)
Making decisions (Case) 8. A worksheet or workbook event, e.g. when a workbook is opened
Looping (Do...Loop) This is maintained in the Visual Basic Editor (VBE) interface.
Looping (For...Loop)
With...End With blocks The last item is a great way to get Excel to run your code without any user intervention as it's uses
User defined functions Excel's own processes to trigger the macro.
Event handling
Error handling Most users will not be aware that Excel constantly listens for events to happen but do not see any
physical results until they learn to manipulate the event handlers provided.
Debugging
Creating User Forms
There are many events from a Control (i.e. Button) to opening (Open) and closing (Close) workbooks.
DAO/ADO Objects
Input/Output Files
Think about how Data Validation and Conditional Formatting work in Excel worksheets. They
respond to when a user has clicked the Enter key (Worksheet_Change) to trigger the two utilities. -
Other links More on this later...
Example code snippets
Userform input example
Next Topic: Where macros are stored
Want to teach yourself Access? Free online guide at About Access Databases
All trademarks are copyrighted by their respective owners. Please read our terms of use and privacy policy.
Back to Excel Homepage Excel VBA - Reference Guide
Note: The full path to locate folders
Range/Selection objects
Object hierarchy 2. New Workbook will store the macro to an unsaved new file and is generally used for distributing to
other users which they would need to load and run manually. Treat this as the same scope for that of
Object browser This Workbook and is deemed as a local macro too.
Chart objects
Pivot Table objects 3. Personal Workbook is a specially reserved named file which is generated (first time around)
Formulas automatically to store the recorded macros.
Visual Basic Functions
Creating Add-Ins The name given to this file (which is still treated like any other Excel file) is Personal.xls/xlsm/xlsb.
Variables & constants
Object variables This file is hidden by default as it is not intended to be used as a normal spreadsheet.
Arrays
Collections The location of the file is important and must reside in the XLSTART folder of where the user's profile
Message Box or Excel application is installed.
Other links
Next Topic: Reasons to write macros
Example code snippets
Userform input example
Want to teach yourself Access? Free online guide at About Access Databases
All trademarks are copyrighted by their respective owners. Please read our terms of use and privacy policy.
Back to Excel Homepage Excel VBA - Reference Guide
Note: If you intend to write macros
Other links
6. Protect data from user errors.
Example code snippets
Instead of allowing users to gain direct access to your data, protecting it via a macro will
Userform input example give you better control in how users can manage your Excel processes.
Viewing the data maybe required in most tasks and allowing users to protect and
unprotect ranges, worksheets and workbooks (with or without passwords) to edit and
format information can be controlled in decision making macros.
User form can also provide a level of protection and require macro VBA code too.
Do not 're-invent the wheel' in other words learn as much as possible about the general features of
Excel to rule out if you really need to have a macro at all.
You may find a feature in Excel can do all your tasks in one simple step and you would have wasted
time creating a macro in the first place.
All trademarks are copyrighted by their respective owners. Please read our terms of use and privacy policy.
Back to Excel Homepage Excel VBA - Reference Guide
Tip: Alt + F11 function keys switches
Note that the text 'January' is entered with speech (double-quote) marks, as it is a piece of text, where
as the number 100 is entered without.
Want to teach yourself Access? Free online guide at About Access Databases
All trademarks are copyrighted by their respective owners. Please read our terms of use and privacy policy.
Back to Excel Homepage Excel VBA - Reference Guide
VBA Keywords: MsgBox, Call, Exit
Menu
There are three types of procedures:
Recording macros
Looking at the code 1. Sub - Standard sub routine
Ways of running macros 2. Function - a routine that returns an answer
Where macros are stored 3. Property - reserved for Class Modules
Reasons to write macros The third item is not discussed in this topic as it is deemed advanced VBA.
Writing macros
Procedure types
Sub Procedure
Visual Basic editor (VBE)
Rules & conventions This is the most commonly used procedure that a recorded and edited macro typically uses.
Excel objects It executes code line by line in order, carrying out a series of actions and/or calculations.
Range/Selection objects The signature for this type of procedure is:
Object hierarchy
Object browser Sub NameOfProcedure([Arguments])
Chart objects 1st line of executed code Comments
Pivot Table objects 2nd line of executed code Comments
Formulas ..........
Visual Basic Functions End Sub
Creating Add-Ins
Variables & constants
The Arguments element is optional which can be explicit or implicit. This allows values and /or
Object variables
references to be passed into the calling procedure and handled as a variable.
Arrays
When recording a macro, no arguments are used and the parenthesis for the named procedure
Collections remains empty.
Message Box If you create a procedure intended as a macro in Excel, users must not specify any arguments.
VBA Input Box Sub procedures can be recursive meaning that branching to another procedure is permitted which
Excel Input Box then returns back to the main calling procedure.
Making decisions (If) Calling another procedure can include the Call statement followed by the name of the procedure with
optional arguments. If arguments are used, users must use parenthesis around the argument list.
Making decisions (Case)
Looping (Do...Loop)
Looping (For...Loop)
Example of the CALL statement
With...End With blocks
Procedure to be called with a single
User defined functions argument explicitly declared as a string
Event handling Sub MyMessage(strText As String)
Error handling MsgBox strText
Debugging End Sub
Creating User Forms
(Click here for an understanding of the MsgBox statement)
DAO/ADO Objects
Input/Output Files
Correct
Test the calling procedure
Other links
Sub TestMessage()
Example code snippets
Call MyMessage("It worked!")
Userform input example
End Sub
A procedure can be prematurely terminated, placed before the End Sub statement by using the Exit
Sub statement.
This procedure will terminate after part A and never run part B.
Sub TerminateNow()
Code part A here...
Exit Sub
Code part B here....
End Sub
Function Procedure
The main difference between a Sub and Function procedure is that a Function procedure carries out
a procedure and will return an answer whereas a Sub procedure carries out the procedure without an
answer.
A simple analogy of a Function procedure compared to that of a Sub procedure could be illustrated
using two example features of Excel:
File, Save is an action and does not return the answer Sub Procedure.
The Sum function calculates the range(s) and returns the answer Function Procedure.
The Arguments element is optional which can be explicit or implicit. This allows values and /or
references to be passed into the calling procedure and handled as a variable.
The optional Type attribute can be used to make the function explicit. Without a type declared, the
function is implicit (As Variant).
The last line before the End Function signature uses the name of the procedure to return the
expression (or answer) of the function.
Users cannot define a function inside another function, sub or even property procedures.
This type of procedure can be called in a module by a Sub procedure or executed as a user defined
function on a worksheet in Excel.
A procedure can be prematurely terminated, placed before the End Function statement by using the
Exit Function statement. This acts and responds in the same way as described in the previous
section (Sub Procedures).
In Excel, this function can also be used (known as a User Defined Function - UDF)
Click on this link for more information on user defined functions.
Want to teach yourself Access? Free online guide at About Access Databases
All trademarks are copyrighted by their respective owners. Please read our terms of use and privacy policy.
Back to Excel Homepage Excel VBA - Reference Guide
Tip: Use F5 function key to run a
Menu
All macros can be edited and created from the Visual Basic Editor (VBE) application as mentioned
Recording macros earlier.
Looking at the code
Ways of running macros
Where macros are stored
Reasons to write macros
Writing macros
Procedure types
Visual Basic editor (VBE)
Rules & conventions
Excel objects
Range/Selection objects
Object hierarchy
Object browser
Chart objects
Pivot Table objects
Formulas
Visual Basic Functions
Creating Add-Ins
Standard Toolbar
Variables & constants
Contains all the basic buttons to this window like save, switching to Excel and hide/show other
Object variables windows. There are other Toolbars available; Edit, Debug, User Form and Toolbox.
Arrays
Collections Object Box
Message Box This displays the name of the selected object chosen from the drop down box.
VBA Input Box
Excel Input Box Procedure Box
Making decisions (If) This displays the name of the procedure or event of the object (i.e. worksheet).
Making decisions (Case)
Looping (Do...Loop) Code Window (Module)
Looping (For...Loop) This is where you maintain the VBA code. One or more sub and function procedures are stored in this
With...End With blocks view and users manage macros across one or more modules.
User defined functions
Event handling Project Explorer
Error handling All the code associated with a workbook is stored in the Project window. This is automatically saved
with the Workbook.
Debugging
Creating User Forms
DAO/ADO Objects
Input/Output Files
Other links
Like a workbook, the Project Explorer contains all associated objects, which include worksheets,
user forms and modules.
Macros are stored in either the sheet object or module object. Consider using the module object to
store macros for general use in that workbook rather than a specific macro for a specific sheet.
By double clicking on an object or clicking the view code button at the top left corner of the Project
window, displays the objects code (macros associated).
Properties Window
Properties are characteristics of the selected object.
This window allows you change these characteristics to a worksheet, workbook and user form.
This above window is task sensitive and therefore changes as you click from one control to another.
Edit Toolbar
Edit Toolbar
2 List Constants.
5 Complete word displays a scroll list box of keywords and completes the beginning of
known types keywords.
8 Toggle Breakpoint allows marking a line of code at which point a macro will stop.
9 Comment Block rem the line (put an apostrophe at the beginning of the line).
11 Toggle Bookmark marks with a blue marker a piece of code so that scrolling between
code lines is quick and simple.
There other toolbars that you may need to review and can be found via the View menu.
Want to teach yourself Access? Free online guide at About Access Databases
All trademarks are copyrighted by their respective owners. Please read our terms of use and privacy policy.
Back to Excel Homepage Excel VBA - Reference Guide
VBA Keywords: If...Then, MsgBox,
Menu
It is not mandatory to follow Microsofts rules and conventions regarding name spaces and prefixes.
Recording macros Users could always introduce their own standards, rules and conventions, which will help other users
Looking at the code who may need to maintain processes within the organisation.
Ways of running macros The following is a guideline to perhaps how authors and users alike could manage the code.
Where macros are stored Naming macros, procedures and variables should be meaningful to the process to help clarify the
task in hand.
Reasons to write macros
Do not name a macro or procedure MyProcedure1 or Macro1 but keep it user friendly to help
Writing macros described the process.
Procedure types Users can use more than one word provided there are no spaces or invalid characters used
Visual Basic editor (VBE) (operators). When using more than one-worded procedures, consider initially capping each word to
Rules & conventions help see the name of the procedure clearly.
Excel objects For example, Sub openallorders() would be better shown as Sub OpenAllOrders().
Range/Selection objects Variables such as X = 10 would be more helpful if X was named to be more meaningful to the
intended process i.e. the number of years and could therefore be shown as NumberOfYears = 10 or
Object hierarchy NoYears = 10.
Object browser
Chart objects Variables and naming conventions are covered elsewhere in this guide see Variables and
Constants.
Pivot Table objects
Formulas
Do not use keywords when naming procedures or variables, as this will cause potential conflicts and
Visual Basic Functions errors.
Creating Add-Ins
Variables & constants Indentation
Object variables
Arrays Code should be clearly positioned in a module. Use the tab key to indent logical blocks of code.
Collections Users can use as many indentations to emphasis new blocks of code (as nested) if required to show
where a block starts and ends. This will help when browsing for long portions of code.
Message Box
VBA Input Box
Excel Input Box
Making decisions (If)
Making decisions (Case)
Looping (Do...Loop)
Looping (For...Loop)
With...End With blocks
User defined functions
Event handling
Error handling
Debugging
Creating User Forms
Comments
DAO/ADO Objects
Input/Output Files
Commenting your code is important to the author and other users who may need to maintain code
fragments. By default, commented lines are coloured green when text is typed following an
Other links apostrophe ( ) or the keyword Rem (remark).
Example code snippets As part of the opening signature (either before or after the signature), a brief description of the
procedure along with a date and name of the author should be documented.
Userform input example
For example:
Sub ProcessInvoice()
'**************************************************************
' This procedure will validate all entries to the new invoice.
' It will calculate sub total and tax values and post it to the
' data store. ' It will print and close the invoice.
' Author: Ben Beitler
' Date Created: 12/04/2010
' Date Modified: 20/04/2010
'**************************************************************
executed code is entered here
End Sub
Comments can appear anyway in the module provided it is remarked correctly as this type of text is
ignored during code execution. Comments should also be added to unusual or difficult lines of code
(known as inline comments) to help explain the nature of the action.
For example:
Sub SomeProcedure()
' Comments here.
Line Breaks
Generally code should not be written beyond the screen/page width as it becomes cumbersome to
work with, as users would have to scroll left and right unnecessarily.
Consider introducing a line break for single line code that extends beyond the page width by using
the characters spacebar and a underscore ( _ ).
For example:
Sub MessageTestLineBreak()
MsgBox "This is the first Line." & vbNewLine & _
"This is the second Line.", _
vbInformation, "Message Box Test"
End Sub
Microsoft produced various documents on this subject. For a full list, check out
http://msdn.microsoft.com/library and search for 'Code Conventions'
More information about conventions regarding variables are covered later in this manual see
Variables & Constants.
Want to teach yourself Access? Free online guide at About Access Databases
All trademarks are copyrighted by their respective owners. Please read our terms of use and privacy policy.
Back to Excel Homepage Excel VBA - Reference Guide
VBA Keywords: Application,
Chart objects
Pivot Table objects Use this object as the entry point (the gateway) to the Excel object model and is implicit which means
that you can omit this keyword in your code as it's the default. The following two VBA commands do
Formulas
the same thing:
Visual Basic Functions
Creating Add-Ins
Application.ActiveSheet.Name = "January"
Variables & constants
Object variables
ActiveSheet.Name = "January"
Arrays
Collections
The first example included the Application object keyword (as explicit) and the second one excluded
Message Box (as implicit) it but produced the same result.
VBA Input Box
Excel Input Box You only need to use this keyword if you are coding with other applications (that is not Excel) or wish
Making decisions (If) to communicate to Excel from another application's environment (i.e. Microsoft Word). You will need to
learn about object variables and set application objects to Excel.
Making decisions (Case)
Looping (Do...Loop)
The following code snippet creates an Excel object from outside of Excel (which uses VBA too) and
Looping (For...Loop)
opens a workbook called "Sales.xlsx":
With...End With blocks
User defined functions
Sub OpenExcelWorkbook()
Event handling
Dim xl As Object
Error handling
Set xl = CreateObject("Excel.Sheet")
Debugging
Creating User Forms xl.Application.WorkBooks.Open("Sales.xlsx")
Input/Output Files
End Sub
Other links
The singular keyword Workbook refers to the current or a single file you wish to control compared
with the plural keyword Workbooks which is the collection of one or more documents you wish to
control
Use the Workbook object referred in code as ActiveWorkbook to open, save, print, close and
manipulate the documents attributes as required.
Sub WorkBookNameExample()
MsgBox "Current workbook is " & ActiveWorkbook.Name
End Sub
Save a copy of the current workbook:
Sub SaveAsWorkBookExample1()
ActiveWorkbook.SaveAs "VBA Workbook.xlsx"
End Sub
Sub SaveAsWorkBookExample2()
Workbooks(1).SaveAs "VBA Workbook.xlsx"
End Sub
Using the Workbooks keyword which is a collection of current workbooks, you can provide an index
number (starting at 1 for the first document and incrementing by 1 for each open document) to execute
code using the same identifiers as ActiveWorkbook object.
Sub WorkBookCount()
MsgBox "There are currently " & Workbooks.Count & _
" workbook(s) open"
End Sub
The Workbooks object doesn't have any parenthesis and an index number reference when dealing
with a collection of many documents.
(Note: the above will also count all open and hidden documents).
Most of the time, you will work with this object along the range object as the normal practice is
worksheet management in a workbook when working with the Excel interface.
Again, the singular Worksheet object referred as ActiveWorkSheet controls the current or single
worksheet objects including its name. The plural keyword Worksheets refers to one or more
worksheets in a workbook which allows you to manipulate a collection of worksheets in one go.
Name a worksheet:
Sub RenameWorksheetExample1()
ActiveWorkSheet.Name = "January"
End Sub
or use
Sub RenameWorksheetExample2()
WorkSheets(1).Name = "January"
End Sub
Insert a new worksheet and place it at the end of the current worksheets:
Sub InsertWorksheet1()
Worksheets.Add After:=Worksheets(Worksheets.Count)
End Sub
Sub InsertWorksheet2()
Sheets.Add After:=Sheets(Sheets.Count)
End Sub
(Note: Have you noticed when adding a new worksheet via Excel interface how it always inserts it to the left of the
active sheet!).
'Active' objects
Within the Application object you have other properties which act as shortcuts (Globals) to the main
objects directly below it. These include ActiveCell, ActiveChart, ActivePrinter, ActiveSheet,
ActiveWindow and ActiveWorkbook.
You use the above keywords as a direct implicit reference to the singular active object in the same
way (as in the above already illustrated).
Remember, you can only have one active object when working in the Excel interface and therefore
the VBA code is emulating the way users are conditioned to work. Even when a range of cells is
selected (Selection object) only on cell is active (the white cell).
Sub PrinterName()
MsgBox "Printer currently set is " & ActivePrinter
End Sub
Want to teach yourself Access? Free online guide at About Access Databases
All trademarks are copyrighted by their respective owners. Please read our terms of use and privacy policy.
Back to Excel Homepage Excel VBA - Reference Guide
Tip: You can refer to Range("A1")
CELLS Property
This property can be used as an alternative to the absolute range property and is generally more
flexible to work with, as variables are easier to pass into it.
There are two optional arguments:
Cells([row] [,column])
Leaving the arguments empty (no brackets), it will detect the current selection as the active range.
Adding an argument to either row or column with a number will refer to the co-ordination of the
number passed.
Adding both arguments will explicitly locate the single cells co-ordinate.
Variables can be passed into the Cells property and then nested into the Range object as in the
following example:
'Two InputBoxes for rows and columns
Sub CellsExample2()
On Error GoTo handler
Dim intRows As Integer
Dim intCols As Integer
intRows = CInt(InputBox("How many rows to populate?"))
intCols = CInt(InputBox("How many columns to populate?"))
'starts at cell A1 to the number of rows and columns passed
Range(Cells(1, 1), Cells(intRows, intCols)).Value = "X"
Exit Sub
handler:
'Error code is handled here...
End Sub
By wrapping a range property around two cell properties, the flexibility of passing variables becomes
apparent.
Error handlers and InputBox functions are covered later in this guide.
Four properties that return the column or row number for the focused range.
The singular (Column or Row) returns the active cells co-ordinate and the plural (Columns or Rows)
can be used to count the current selections configuration.
Sub ColRowExample()
MsgBox "Row " & ActiveCell.Row & _
" : Column " & ActiveCell.Column
End Sub
Sub ColsRowsCountExample()
MsgBox Selection.Rows.Count & " rows by " _
& Selection.Columns.Count & " columns selected"
End Sub
CURRENTREGION Property
Selects from the active cells position all cells that are adjacent (known as a region) until a blank row
and blank column breaks the region.
Use this statement to select a region.
Selection.CurrentRegion.Select
To select a region of data and exclude the top row for a data list:
Make sure the active cell is in the region of data you wish to capture before running the above
procedure.
RESIZE Property
Sub ResizeRange()
Dim rows As Integer
Dim cols As Integer
cols = Selection.Columns.Count
rows = Selection.rows.Count
Selection.Resize(rows + 1, cols + 1).Select
End Sub
Resizing a range can be increased, decreased or change the configuration (shape) by combining
positive and negative values inside the Resize propertys arguments.
OFFSET Property
This property is used in many procedures as it controls references to other cells and navigation.
Two arguments are passed into this property that is then compounded with either another property or
a method.
Selection.OffSet(1, 2).Select
ActiveCell.OffSet(0, -1).Value = "X"
Consider referring to an offset position rather than physically navigating to it this will speed up the
execution of code particularly while iterating.
For example:
Sub OffSetExample1()
Dim intCount As Integer
Do Until intCount = 10
ActiveCell.Offset(intCount, 0).Value = "X"
intCount = intCount + 1
Loop
End Sub
Sub OffSetExample2()
Dim intCount As Integer
Do Until intCount = 10
ActiveCell.Value = "X"
ActiveCell.Offset(1, 0).Select
intCount = intCount + 1
Loop
End Sub
Do...Loops (iterations) are covered later in this guide
The above two examples produce the same result but instead of telling Excel to move to the active
cell and then enter a value, it is more efficient to refer (or point) to the resulting cell and remain in the
same position.
A positive value for the column argument refers to a column to its right.
A negative value for the column argument refers to a column to its left.
Be careful to introduce error-handling procedures when working with the Offset property as if you
navigate or refer to a position outside the scope of the fixed dimensions of a worksheet, this will
certainly cause a run time error (See Error Handling & Debugging).
ACTIVATE Method
This method should not be confused with the Select method as commonly used in VBA.
The Select method means go and navigate to it.
Range(A1).Select.
Range(A1:C10).Select
to
CLEAR Methods
These methods simulate the windows clipboard cut, copy and paste commands.
There are a few different types of these methods where most arguments are optional and by changing
the argument settings, will change the behaviour of the method.
Some examples:
'Simple Copy and Paste
Sub CopyPasteData1()
Range("A1").Copy
Range("B1").PasteSpecial xlPasteAll
End Sub
These methods can add or remove cells, rows or columns and is best used with other properties to
help establish which action to execute.
Some examples:
'Inserts an entire row at the active cell
Sub InsertRow()
ActiveCell.EntireRow.Insert 'or EntireColumn
End Sub
Users can create and set a range object instead and like all other object declarations, use the Set
command (which is used for object variable declarations).
For example, using a For...Loop (see For...Loop section about this control flow), iterating in a
collection is carried out by declaring and setting a variable as a Range object:
'Loops through the elements of the Range object
Sub IterateRangeObject()
Dim r1 As Range
Dim c As Object
Set r1 = Range("A1:C10")
For Each c In r1
If c.Value = Empty Then
c.Value = "0"
End If
Next c
End Sub
The above procedure checks each cell in a fixed range (A1 to C10) and determines its value, placing
a 0 (zero) if the cell is empty.
Want to teach yourself Access? Free online guide at About Access Databases
All trademarks are copyrighted by their respective owners. Please read our terms of use and privacy policy.
Back to Excel Homepage Excel VBA - Reference Guide
VBA Keywords: Application,
Input/Output Files
Identifying the Objects, Methods and Properties from the previous example.
Other links
Examples
Properties
A Property is an attribute of an object, e.g. the colour of a car, the name of a worksheet.
Object.Property = Value
Car.Colour = Red
Worksheets(Sheet1).Name = "My Sheet"
Methods
A Method is an activity that an object can be told to do, e.g. accelerate the car, select a cell, insert a
worksheet, delete a worksheet.
Object.Method
Car.Accelerate
Range("A2:A10").Select
The following example will select a range of cells (A2 to A10) in the current worksheet.
There are methods that contain many arguments, for example inserting a worksheet(s). The
numerous arguments contain information about how many worksheets you would like to insert, the
position of the worksheet(s) and the type of the worksheet(s).
Object.Method Argument1,Argument2,...
Example:
Worksheets.Add Before, After, Count, Type
Worksheets.Add, Sheets(Sheet2), 2
Sub Insert2Sheets()
Worksheets.Add Sheets("Sheet2"), 2
End Sub
Events
Events are like Methods the only difference being when and who/what calls this action. It is an action
like a method but the system will trigger it for you instead of the user invoking the action.
This is very useful when a system changes state and needs to automate a procedure on behalf of the
user.
In fact, there are many events being triggered all the time; users are simply not aware of this unless
there is a procedure to trigger it. The system constantly listens for the event to take place.
When you use standard Excel features like Data Validation or Conditional Formatting, the system
automatically creates code for an event so when users enter a value in a cell it will automatically
trigger the feature and validate and format the active cell without a user calling the a macro manually.
This type of event is normally known as 'Enter' for a Worksheet.
There are many predefines events which have no code just a starting and ending signature and users
need to add code in between these signatures. Take a look at Event Handling for more information.
Want to teach yourself Access? Free online guide at About Access Databases
All trademarks are copyrighted by their respective owners. Please read our terms of use and privacy policy.
Back to Excel Homepage Excel VBA - Reference Guide
Tip: You can press F2 function key
Menu
The Object Browser enables you to see a list of all the different objects with their methods, properties,
Recording macros events and constants.
Looking at the code
Ways of running macros In the VBE editor:
Reasons to write macros 2. Click on the View menu and select Object Browser (shortcut key: F2).
Procedure types
Visual Basic editor (VBE)
Rules & conventions
Excel objects
Range/Selection objects
Object hierarchy
Object browser
Chart objects
Pivot Table objects
Formulas
Visual Basic Functions
Creating Add-Ins
Variables & constants
Object variables
Arrays
Collections
Message Box
VBA Input Box
Excel Input Box
Making decisions (If)
Making decisions (Case)
Notice Add([Before], [After], [Count], [Type]) is one of the examples previously seen.
Looping (Do...Loop)
Looping (For...Loop)
The main two panes contain on the left Classes (also known as Objects) and on the right Members
With...End With blocks
(also known as Identifiers).
User defined functions
By selecting a class, you display its members which are of three key types; Properties, Methods and
Event handling Events.
Error handling
Debugging Libraries
Creating User Forms
DAO/ADO Objects Libraries are the application divisions of a collection of classes (objects). Therefore, you will have a
Input/Output Files class for Excel, VBA and other applications you wish to have a reference to. The Excel (the host),
VBA and VBAProject are mandatory and can not disabled. All other library files can be switched on
or off as required.
Other links
To switch between libraries or show all libraries, choose the Project/Library drop down box:
Other libraries are also available but require to be enabled before they can be used which include
Word, Outlook, DAO, ADODB and many others.
By enabling the additional libraries, developers can start to code and communicate with other
applications and processes, which start to reveal the potential power of Visual Basic (VBA).
To enable a library, from the Visual Basic Editor, choose Tools menu and select References
Scroll down to find the required library or choose the Browse button to locate the required library.
Excluding the top two libraries, a library priority order matters that is why users can re-arrange the
order using the Priority buttons. The way the system works is when a procedure is executed, it checks
to see which library is required in order to execute the line-by-line code. In some cases, a method or
class can be duplicated between libraries and it is therefore important to be able to call the correct
method or class first superseding the lower level references.
Structure of a Library
Each Library will typically have a collection of classes. A class or object class is in essence the
object i.e. Worksheet.
Each object class will have a collection of members, which could be a collection of properties,
methods and events.
When looking at the Object Browser, users will see on the left hand side many classes to the active
library. To the right hand pane, all members of the selected class will reveal properties, methods and
events.
The above illustration shows the Excel library, Worksheet class and the Visible property highlighted
(Excel.Worksheet.Visible).
Right mouse click the selected item to choose the Help command and go straight to the offline help
documentation.
Browsing the right hand and pane of the Object Browser, users will see three different icons to help
identify the member type:
Browser Searching
The search tool allows users to locate if a keyword firstly exists and secondly where it could possibly
reside
At the top half of the browser window, type the desired keyword and then click the search button:
The above example looked for the keyword visible across all libraries.
After locating the correct item (selecting the item), users can use the copy button function and then
paste into a code window.
Want to teach yourself Access? Free online guide at About Access Databases
Home | Terms of Use | Privacy Policy | Contact
copyright 2010 TP Development & Consultancy Ltd, All Rights Reserved.
All trademarks are copyrighted by their respective owners. Please read our terms of use and privacy policy.
Back to Excel Homepage Excel VBA - Reference Guide
VBA Keyword: ActiveSheet,
Defining object variables for longer based procedures makes the code more clinical and efficient to
write even though we must first declare a new object (as ChartObject).
Sub WrittenMacroChartObject()
Dim ChrtObj As ChartObject
Set ChrtObj = ActiveSheet.ChartObjects.Add _
(Left:=100, Width:=400, Top:=100, Height:=250)
ChrtObj.Chart.SetSourceData Source:=Sheets("Sheet2").Range("A2:D12")
ChrtObj.Chart.ChartType = xlXYScatterLines
End Sub
The above example is the same as the previous code snippet but using the object variable ChrtObj
as declared and set.
The other useful method is SetSourceData as you can add as many series as required (one at a
time) enabling what ranges you want to set and not let Excel make as assumption.
Adding Series
When recording a macro adding a series each line of code is created for a name, y-axis values and x-
axis values if required using SeriesCollection and NewSeries keywords.
An example of recorded macro which adds three series (names and values) and an y-axis to an
existing empty chart on a worksheet:
Sub AddingSeries()
ActiveChart.SeriesCollection.NewSeries
ActiveChart.SeriesCollection(1).Name = "='Sheet2'!$B$2"
ActiveChart.SeriesCollection(1).Values = "='Sheet2'!$B$3:$B$12"
ActiveChart.SeriesCollection.NewSeries
ActiveChart.SeriesCollection(2).Name = "='Sheet2'!$C$2"
ActiveChart.SeriesCollection(2).Values = "='Sheet2'!$C$3:$C$12"
ActiveChart.SeriesCollection.NewSeries
ActiveChart.SeriesCollection(3).Name = "='Sheet2'!$D$2"
ActiveChart.SeriesCollection(3).Values = "='Sheet2'!$D$3:$D$12"
ActiveChart.SeriesCollection(3).XValues = "='Sheet2'!$A$3:$A$12"
End Sub
Using the With...End With statement will refine the code and make it easier to understand. Also,
introducing your own objects for a series just gives you better control should you wish to assign
variables and arrays to it.
Remember, you can pass variables better into the above example code (not illustrated).
Using arrays and collections, you have better control especially when wanting to handle multiple
charts in one go.
Want to teach yourself Access? Free online guide at About Access Databases
All trademarks are copyrighted by their respective owners. Please read our terms of use and privacy policy.
Back to Excel Homepage Excel VBA - Reference Guide
VBA Keywords: PivotCaches,
Input/Output Files
When the system adds a new worksheet Sheets.Add it generates a unique name each time (which is
absolute). Later in the procedure it refers to the name of new added worksheet (which is why it fails
Other links
when running the macro).
Example code snippets
Userform input example Instead of referring to TableDestination:="Sheet1!R3C1" in the Pivot objects TableDestination
argument, consider using this code TableDestination:=ActiveSheet.Cells(1, 1)instead
which picks the current worksheets cell A1.
Remove the line Sheets("Sheet1").Select and the rest of the code should now work as recorded.
Now lets take a look at the Pivot Table object itself and build the knowledge so that you understand
the elements and arguments correctly.
Use the Create and CreatePivotTable methods of the PivotCaches object:
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, _
SourceData:="Sales List!R1C1:R306C13", _
Version:=xlPivotTableVersion10).CreatePivotTable _
TableDestination:=ActiveSheet.Cells(1, 1), _
TableName:="PivotTable1", DefaultVersion:=xlPivotTableVersion10
Note: In Excel 2003 (or earlier) users tend to use the Add method instead of the Create method which has its
own set of arguments.
The SourceData argument is a range reference to the data list source. Also note this reference in the
above example is an absolute reference too and should be careful should the data source change
and grow dynamically. Consider using a variable or object variable to hold the current address of a
region of data to pass into the Create method.
For example (before adding the new worksheet - Sheets.Add) include the following:
Selection.CurrentRegion.Select
MyDataRef = Selection.Address
The TableDestination argument pinpoints where the starting cell in a worksheet (normally a new
worksheet) is and should really be dynamic and relative (as previously mentioned).
The remaining arguments are optional but as the macro records distinct settings they have been
included. Refer to the Excel VBA help files for further information.
Pivot Tables are objects and can given a unique name as in the above example shown called
"PivotTable1".
Using the named object, you can then refer to elements in a Pivot Table which include PivotFields
collections and their properties; Orientation, Position and calculated functions.
Sub SummaryPivotReport()
End Sub
The above example will give you better control and more flexibility in defining a Pivot Table without
have to ensure your have added a new worksheet, placed the cursor in the right position and any
duplicate name references (worksheets).
Next Topic: Formulas
Want to teach yourself Access? Free online guide at About Access Databases
All trademarks are copyrighted by their respective owners. Please read our terms of use and privacy policy.
Back to Excel Homepage Excel VBA - Reference Guide
Note: Your knowledge of Excel
Menu
+, - Addition/Subtraction 5
Other links
<, <=, >, >= 6
Example code snippets
Like 7
Userform input example
There are more operators that fit in between the above table. Refer to on-line Help or Users Guide.
Concatenate (&)
Concatenate is the term used to join two or strings (text values) together. You use the & (ampersand)
as the operator (the glue) to connect one string to another.
This is commonly used in VBA to build string messages and narratives which will part static and
dynamic (variables) enhancing the procedure to a more user friendlier environment.
For example, to join my first name with my surname with a space between the two using two variables
and a static string (space) between:
Sub ConcatenateExample()
Dim FName As String, SName As String
FName = "Ben"
SName = "Beitler"
MsgBox "Welcome " & FName & " " & SName
End Sub
Constants
A Constant is a value in a macro that does not change. By using constants, is similar to variables
where a value is assigned to the variable.
For example:
Variable known as TitleHeading can have a value assigned to it.
TitleHeading = SALES CASH FLOW for JANUARY
Every time the value is used, by using the variable it is easier to handle, update changes and
therefore more efficient.
To assign a named constant, proceed with the command Const before the variable.
For example
Variable known as pi can have a value of 3.1415926 assigned to it. Since this is a fixed value for pi,
assign the Const command to it.
Const PI = 3.1415926
Functions
Arguments
Some functions and statements will contain required and optional arguments. An argument is an
element of that function or statement which is required to apply that command. Arguments either use a
comma separator or can use its syntax name.
For example:
Absolute Formula
Similar to the Absolute Macros we looked at earlier, an Absolute Formula will refer to specific cell
references.
Sub formula()
ActiveCell.Formula = "=Sum(A1:A4)"
End Sub
Relative Formula
Similar to the Relative Macros we looked at earlier, a Relative Formula will refer to the active cell and
the other cells around it.
Sub formula()
ActiveCell.FormulaR1C1 = "=Sum(r[-4]c:r[-1]c)"
End Sub
Instead of using cell references in the formula, i.e. A1:A4, the relative formula uses row and column
references, i.e. r[-4]c:r[-1]c.
In the above example, r[-4]c refers to the cell 4 rows above the active cell in the same column and
r[-1]c refers to the cell 1 row above the active cell in the same column.
Next Topic: Visual Basic Functions
Want to teach yourself Access? Free online guide at About Access Databases
All trademarks are copyrighted by their respective owners. Please read our terms of use and privacy policy.
Back to Excel Homepage Excel VBA - Reference Guide
Note: The VBA library is the top most
INFORMATION Class
This class is a collection of status functions to help evaluate conditions of variables and objects alike.
Some functions in the class:
IsArray(variant) returns true or false
IsDate(expression) returns true or false
IsError(expression) returns true or false
IsEmpty(expression) returns true or false
IsMissing(variant) returns true or false
IsNull(expression) returns true or false
IsNumeric(expression) returns true or false
IsObject(expression) returns true or false
An expression or variant is the variable being tested to see if it is True or False.
MATH Class
This class is a collection of mathematical functions that can be used to change variables with ease
and without having to create your own functions.
Some functions in the class:
Abs(Number) returns the absolute number (always a positive value)
Rnd([Number]) returns a random value
Round(Number, [NumDigitsAfterDecimal]) returns a rounded value
Sqr(Number) returns a square value (x2 )
STRING Class
This class is a collection of text (string) based functions that include conversion, extractions and
concatenation.
Some functions in the class:
Asc(String) returns the numeric ASCII value of the character string
Chr(CharCode) returns the character string from the code supplied
Format(Expression, [Format], [FirstDayOfWeek], [FirstWeekOfYear])
- returns the format presentation of the expression
InStr([Start], [String1], [String2], [Compare]) returns the numeric position of the first character found
from left to right
InStrRev(StringCheck, StringMatch, [Start], [Compare]) returns the numeric position of the first
character found from right to left
LCase(String) returns the string in lowercase
UCase(String) returns the string in uppercase
Left(String, Length) returns the remaining characters from the left of the length supplied
Right(String, Length) returns the remaining characters from the right of the length supplied
Len(Expression) returns a value of the length of characters supplied
Mid(String, Start, [Length]) returns the portion of characters as determined by the start and end
parameters supplied
Trim(String) removes unwanted spaces from left and right of the string supplied and extra spaces in
between multiple strings
Sub StringExample1()
Dim strString As String
strString = "Microsoft Excel VBA"
'Returns 17 (17th character starting from first character)
MsgBox InStr(1, strString, "V", vbTextCompare)
'Returns 7 (7th character from left starting at the sixth position)
MsgBox InStr(6, strString, "o", vbTextCompare)
End Sub
Sub StrngExample2()
Sub StrngExample2()
MsgBox Format(12.5 * 1.175, "0.00")
End Sub
Which Library?
The MsgBox statement and function and InputBox function are members of the Interaction class in
the VBA library.
Want to teach yourself Access? Free online guide at About Access Databases
All trademarks are copyrighted by their respective owners. Please read our terms of use and privacy policy.
Back to Excel Homepage Excel VBA - Reference Guide
Tip: To switch between Excel
Menu
Add-Ins are wrapped procedures in an independent file for distributing and loading into other Excel Use F12 function in Excel to run the
Recording macros systems. 'Save As' command.
Looking at the code When creating an Add-In, prepare all the procedures, objects and other elements as you would VBA Keywords: Application,
normally prepare a spreadsheet and test it out thoroughly. CommandBars, Controls, Caption,
Ways of running macros Add, OnAction and Delete.
Where macros are stored Therefore, it is not uncommon to have a normal Excel file (xls/xlsx/xlsm/xlsb) and eventually an add-
in file (xla/xlam) of the same information. From the xls file, users save as an xla file that allows for
Reasons to write macros easier upgrade and maintenance.
Writing macros An Add-In file can reside anywhere as the user can control where to point and load the file.
Procedure types An Add-In file is in essence and invisible loaded file which can not physically be edited.
Visual Basic editor (VBE)
Rules & conventions Creating the Add-In file
Excel objects
Range/Selection objects Prepare all the code including any functions, forms and other objects required for distribution.
Object hierarchy
Object browser The saving action is within the Excel interface (as you normally save a file) but you may want to
Chart objects change a few properties within the module especially applying a password protection to your code.
Pivot Table objects
Formulas In the module, right-mouse click the VBAProject node in the Project Explorer view and choose
VBAProject Properties... from the pop-up menu.
Visual Basic Functions
Creating Add-Ins
In the first tab, set the narratives as required.
Variables & constants
Object variables
Arrays
Collections
Message Box
VBA Input Box
Excel Input Box
Making decisions (If)
Making decisions (Case)
Looping (Do...Loop)
Looping (For...Loop)
With...End With blocks
User defined functions
Event handling
Error handling
Debugging
Creating User Forms
DAO/ADO Objects
Input/Output Files
Other links (Note: The Project Name property can not contain any spaces).
Example code snippets
Userform input example Click on the Protection tab and set a password which is case sensitive and make sure you enable the
tick Lock project for viewing.
Choose the OK button to apply.
The next time a user tries to view the code by expanding the node they will be prompted for a
password.
Back in Excel, save your current file (xls/xlsx/xlsm) as an open copy before choosing save as (F12
function key).
Choose the Add-In file type and choose a location to store you copy file.
A copy is generated and the original remains as your working copy which is required should you want
to re-generate a newer version.
All Add-In files are read-only and therefore can not be edited and saved.
To load and install the file you use the Add-In manager tool (and not file, open).
Click on the Office button and choose Excel Options at the bottom of the menu.
Click on the Add-Ins category (on the left pane) followed by the Go... button (at the bottom of the main
screen.
Special reserved events exist for an Add-In file which is executed as the Add-In is loaded and
unloaded into Excel.
Developers typically use these events to control the initialisation and resetting of command bars and
menus amongst other object changes.
The two events are:
1. Workbook_AddinInstall()
2. Workbook_AddinUninstall()
The events can be found by loading the module to ThisWorkbook (node) and choose Workbook from
the Object drop-down control.
On the right hand drop down box (Procedure), scroll for the above two events and type the code
required.
Example use for the above events:
'Creates a menu item too the Tools menu
Private Sub Workbook_AddinInstall()
Dim cb As CommandBarControl
Set cb = Application.CommandBars("Tools") _
.Controls.Add(Type:=msoControlButton)
With cb .BeginGroup = True
.Caption = "My Report..."
.FaceId = 0
.OnAction = "MyReport"
End With
End Sub
The above procedure creates and appends a menu item to the existing Tools menu (Ribbon Bar).
The OnAction property assigns the macro procedure that is called when the item is clicked.
'Removes a menu item from the Tools menu
'If it can be found.
Private Sub Workbook_AddinUninstall()
Dim cb As CommandBarControl
Dim cbt As Integer, i As Integer
i = 1 cbt = Application.CommandBars("Tools").Controls.Count
Do Until i > cbt
Set cb = Application.CommandBars("Tools") _
.Controls.Item(i)
If cb.Caption = "My Report..." Then
cb.Delete
Exit Do
End If
Loop
End Sub
The above procedure removes the custom menu item if it can be found, resetting the Tools menu bask
to default.
Both procedures should be completed with error handling procedures to prevent unnecessary errors
occurring.
(Note: The above example code to install and uninstall was based on Excel version 2003).
Want to teach yourself Access? Free online guide at About Access Databases
All trademarks are copyrighted by their respective owners. Please read our terms of use and privacy policy.
Back to Excel Homepage Excel VBA - Reference Guide
Tip: Remember to enable Option
Example:
The following example declares the MySheet variable to be a String.
Sub VariableTest()
Dim MySheet As String
MySheet = ActiveSheet.Name
ActiveCell.Value = MySheet
End Sub
The position of the declaration statement is important as it determines whether the variable is
available for use throughout the module or just within the current procedure (see Understanding
Scope & Visibility later in this section).
Another Example:
The following example declares the MyData variable to be an Integer.
Sub VariableTest()
Dim MyData As Integer
MyData = ActiveWorkbook.Name
ActiveCell.Value = MyData
End Sub
However, when you run this macro, an error will occur because
MyData = ActiveWorkbook.Name is invalid since ActiveWorkbook.Name is not an Integer but a
String.
When you click on the Debug button, it will highlight incorrect code.
But if you declare MyData as String (i.e. text) then MyData = ActiveWorkbook.Name will
become valid.
Dim MyData As String
If you do not specify a data type, the Variant data type is assigned by default. Variant variables
require more memory resources than most other variables. Therefore, your application will be more
efficient if you declare the variables explicitly and with a specific data type.
Explicitly declaring all variables also reduces the incidence of naming-conflict errors and spelling
mistakes.
Following the conventions set by Microsoft (see Rules and Conventions), variables too have a
standard that in most cases is recommended.
A variable declared explicitly, should have a prefix in lowercase preceding the variable meaningful
name. For example, a variable to store the vat amount of type Double may be shown as
dblVatAmount where dbl is the prefix for a Double data type and the two word variable (initial
capped) referring to the purpose of the variable.
The table below shows what prefixes could be used for each common data type:
By default, all variables not explicitly defined are Variant (the largest memory allocation reserved).
The exception to the above (developers can decide whether to follow the above or not) is when
defining Sub and Function procedures with arguments. As part of the signature of such a procedure,
it can be clearer to the end user to see meaningful named arguments rather than the conventions
stated in the above table.
For example, which is clearer for the end user to understand?
When calling this function within Excel, users will see the arguments via the Insert Function paste
command:
Constants
Constants are values that do not change. They prevent you from having to repeatedly type in large
pieces of text.
The following example declares the constant MYFULLNAME to equal "Ben Beitler". Therefore,
wherever MYFULLNAME has been used, the value that will be returned will be "Ben Beitler".
Sub ConstantTest()
Const MYFULLNAME As String = "Ben Beitler"
ActiveCell.Value = MYFULLNAME
ActiveCell.EntireColumn.AutoFit
End Sub
Implicit Declaration
As previously mentioned, if you do not declare your variables and constants, they are assigned the
Variant data type, which takes up more resources and spelling mistakes are not checked.
A Variant Variable/Constant can contain any type of data.
Data = 10
Data = "Fred"
Data = #01/01/2010#
When you run the following macro, the value in the active cell will be 10.
Sub ImplicitTest()
data = 10
ActiveCell.Value = data
End Sub
When you run the following macro, the value in the active cell will be Fred.
Sub ImplicitTest()
data = "Fred"
ActiveCell.Value = data
End Sub
This can lead to errors and memory abuse though VBA is relaxed in using variables this way - it's just
not good practice!
If you type Option Explicit at the top of the module sheet, you must declare all your variables and
constants.
If you dont declare your variables/constants you will get the following message.
If you wish to ensure that Option Explicit is always entered at the top of the module:
1. Go into the Visual Basic Editor.
2. Click on the Tools menu, select Options...
3. Click on the Editor tab and select "Require Variable Declaration".
You now must always use the Dim keyword to declare any variable.
Variables and procedures can be visible or invisible depending on the following keywords used:
1. Private
2. Public
3. Static
4. Friend (Class Modules only not covered in this guide)
Depending where users use the above keywords, visibility can vary too within a module, class
module or user-form.
In a standard module when using the keyword Dim to declare a variable.If the variable is outside a
procedure and in the main area of the module, this variable is automatically visible to all procedures
in that module. The lifetime of this variable is governed by the calling procedure(s) and can be carried
forward into the next procedure within the same module.
If a variable declared with the Dim keyword is within a procedure, it is visible for that procedure only
and the lifetime of the variable expires when the procedure ends.
The Dim keyword can be used in either the module or procedure level and are both deemed as
private to the module or procedure.
Instead of using the Dim keyword, it is better practice to use the Private keyword when declaring
variables at the module level. Users must continue to use the Dim keyword within a procedure.
Using Public to declare a variable at the module level is potentially unsafe as it is exposed beyond
this module to all other modules and user-forms. It may also provide confusion if the two variables
with the same name exist across two modules. When a variable is declared Public , users should
take caution and try and be explicit in the use of the variable.
For example:
Module A
Option Explicit
Public intMonth As Integer
code continues..........
Module B
Option Explicit
Private intMonth As Integer
Sub ScopeVariables()
intMonth = 10 'This is ModuleBs variable
ModuleA.intMonth = 10 'This is ModuleAs variable (explicit)
End Sub
code continues..........
Two variables with the same name and data type were declared in both module A and B. A procedure
in module B calls the local variable and then explicitly calls the public variable declared in module A.
Users must therefore use the notation of the name of the module followed by the period separator ( . )
and its variable.
Public and Private keywords can also be applied to a procedure. By default, in a standard module,
all procedures are Public unless explicitly defined as Private.
It is good practice to apply either Public or Private for each procedure as later releases of Visual
Basic may insist on this convention.
If a procedure is Private, it can only be used within the module it resides. This is particularly
designed for internal procedures being called and then discarded as part of a branching routine
(nested procedures).
If users mark a procedure as Private, it cannot be seen in the macros dialog box in Excel.
Static Variables
Using the Static keyword allows users to declare variables that retain the value from the previous
calling procedure.
Example using Dim:
'Standard variable (non-static).
Sub TotalValue()
Dim intValue As Integer
intValue = 10
Msgbox intValue
End Sub
Example using Static:
'Standard variable (non-static).
Sub TotalValue()
Static intValue As Integer
intValue = 10
Msgbox intValue
End Sub
Running the first example will simply display the value 10 and the variables value will be lost when
the procedure ends.
Running the second example will display the value 10 but it will retain the variable and its value in
memory so that when running it once more, the value displayed now equals 20 and so on until the file
is either closed or the reset command is executed.
Static can only be used in a procedure and is therefore private.
Const keyword can be public or private (private by default) declared at the module and private only at
the procedure level.
User forms, which allow users to design custom form interfaces, also have scope issues using
Private and Public
By default, any controls event that is drawn onto a form will be private as the form should be the only
object able to call the procedure.
Other event driven procedures, which can be found in a worksheet or a workbook, will also be private
by default.
Passing arguments is a procedure can be either by value (ByVal) or by reference (ByRef). Both
keywords precede the argument name and data type and if omitted is ByRef by default.
When passing an argument by value, the value is passed into a calling procedure
and then lost when the procedure ends or reverts back to the original value as it
returns to the original procedure.
ByVal example:
Sub CustomSub(ByVal AddTo As Integer)
AddTo = AddTo + 5
MsgBox AddTo
End Sub
Sub TestVariable()
Dim x As Integer
x = 5
Call CustomSub(x)
MsgBox x
End Sub
The procedure TestVariable starts by seting x = 5. Its CustomSub procedure is called passing the
variables value of x and incremented by 5. The first message box seen is via the CustomSub
procedure (shows the value 10). The second message box is via the TestVariable procedure which
follows as it returns the focus (shows the value 5). Therefore the ByVal AddTo variable stored is lost
as it is passed back into the original call procedure (TestVariable) resulting in x being equal to 5
again.
ByRef example:
Sub CustomSub(ByRef AddTo As Integer)
AddTo = AddTo + 5
MsgBox AddTo
End Sub
Sub TestVariable()
Dim x As Integer
x = 5
Call CustomSub(x)
MsgBox x
End Sub
The procedure TestVariable starts by seting x = 5. Its CustomSub procedure is called passing the
variables value of x and incremented by 5. The first message box seen is via the CustomSub
procedure (shows the value 10). The second message box is via the TestVariable procedure which
follows as it returns the focus (shows the value 10 again). Therefore the ByRef AddTo variable stored
is not lost as it is passed back into the original call procedure (TestVariable) resulting in x now being
equal to 10.
Want to teach yourself Access? Free online guide at About Access Databases
All trademarks are copyrighted by their respective owners. Please read our terms of use and privacy policy.
Back to Excel Homepage Excel VBA - Reference Guide
Note: You may want to search for
It is good practice to set all object variables to Nothing at the end of the lifecycle of the variable even
though Visual Basic will destroy all variables and pointers automatically once the routine has ended.
It is possible to have an object variable allocated to memory after the event of an error occurring. If the
error handler allows the procedure to continue, it may be necessary to re-set the same object
variable. This is when an object should be destroyed and then re-initialised.
At the end of a procedure, destroy all object variables in the following manner:
For example:
Want to teach yourself Access? Free online guide at About Access Databases
All trademarks are copyrighted by their respective owners. Please read our terms of use and privacy policy.
Back to Excel Homepage Excel VBA - Reference Guide
Note: When you work with arrays
Other links
In the event of preserving the previous size array and wanting to extend the size, users can use
Preserve keyword.
Example code snippets
Userform input example
ReDim Preserve strWeek(14)
Multi-Dimension Array
Array Function
Another way to set values to an array variable is to use the VBA Array function:
Sub ArrayFunctionExample()
Dim strWeek As Variant
Dim strDay As String
strWeek = Array("Sunday", "Monday", "Tuesday", _
"Wednesday", "Thursday", "Friday", "Saturday")
strDay = strWeek(2) ' strDay now contains "Tuesday".
.......................
End Sub
The Array function returns a Variant data type and therefore must be declared as a variant. Each
element can be converted into a string type as required. The first item in the Array function equals
element zero and so on.
In some programming languages, it is not uncommon to have the first element of an array to be equal
to one instead of zero. In situations that the procedure needs to simulate this environment, users can
use the following statement:
Option Base 1
This is declared at the top of the module before the first procedure and affects the entire module. The
value 1 changes the base element to one.
IsArray Function
This function can be used to test if a variable is an array and return either True or False.
Sub ArrayFunctionExample()
Dim strWeek As Variant
Dim strDay As String
strWeek = Array("Sunday", "Monday", "Tuesday", _
"Wednesday", "Thursday", "Friday", "Saturday")
MsgBox IsArray(strWeek) 'True.
MsgBox IsArray(strDay) 'False.
.......................
End Sub
Both bound functions return a Long value of the highest (upper) and the lowest (lower) element
number for an array variable.
Two arguments, one optional:
The optional second argument only applies if the array is a multi-dimensioned array variable.
Sub UpperArray()
Dim intMulti(1 To 5, 1 To 10) As Integer
Dim intUpper As Integer
intMulti(1, 1) = 10
intMulti(2, 1) = 20
intMulti(3, 1) = 30
intMulti(4, 1) = 40
intMulti(5, 1) = 50
intMulti(1, 2) = 60
intMulti(2, 2) = 70
.......................
intMulti(5, 10) = 500
.......................
MsgBox UBound(intMulti, 1) 'shows 5
MsgBox UBound(intMulti, 2) 'shows 10
.......................
End Sub
All trademarks are copyrighted by their respective owners. Please read our terms of use and privacy policy.
Back to Excel Homepage Excel VBA - Reference Guide
VBA Keywords: MsgBox,
Writing macros
A workbook is a member of the collection Workbooks.
Procedure types
Visual Basic editor (VBE) A worksheet is a member of the collection Worksheets.
Other links The above example will close all workbooks in Excel excluding the active workbook and
automatically save any changes.
Example code snippets
Userform input example
Like arrays, elements in a collection can also be referred to directly as an independent item. For
example, to refer to the first worksheet in a workbook:
Sheets(1).Name
Worksheets(1).Name
The array element starts at 1 and increments for each member known to the collection. An error will
happen if the element number is not known (a zero or a number higher than the upper bound
number).
There are many methods and properties to many objects as the Object Browser has shown.
Collections are being used in a lot of situations without the user even being aware.
For example:
Worksheets.Add Count:=2, Before:=Sheets(1)
Worksheets.Add Count:=2, Before:=Sheets(1)
The Add method and some of its arguments inserts two new worksheets to the collection worksheets
and places them before the first element of the worksheets collection.
Want to teach yourself Access? Free online guide at About Access Databases
All trademarks are copyrighted by their respective owners. Please read our terms of use and privacy policy.
Back to Excel Homepage Excel VBA - Reference Guide
VBA Keyword: MsgBox
Other links
Example2 - MsgBox Function (Multiple Lines):
Example code snippets
Sub MultiLineMessageBox()
Userform input example Dim intResponse As Integer
intResponse = MsgBox("You have chosen to save this file." _
& vbNewLine & "Do you wish to proceed?" & vbNewLine & _
"Click 'Yes' to save or 'No' to close and not save.", _
vbQuestion + vbYesNoCancel, "Save File")
....................................
End Sub
The above example will display multiple lines in the message box using the constant vbNewLine.
Constants for MsgBox
Buttons and icons are combined for the Buttons argument which have a unique value that drives the
output of how users use and see button combinations:
The following applies to the MsgBox Function when the user clicks a button returning a unique value.
vbOK 1 OK
vbCancel 2 Cancel
vbAbort 3 Abort
vbRetry 4 Retry
vbIgnore 5 Ignore
vbYes 6 Yes
vbNo 7 No
While a the MsgBox is being displayed, the macro procedure is paused waiting for the user to click a
button whether it is a statement or a function.
Note the difference between the two types regarding when parenthesis are used and can be ignored.
Also, be aware any function must be placed to the right side of an = (equal sign) because it returns an
answer.
Want to teach yourself Access? Free online guide at About Access Databases
All trademarks are copyrighted by their respective owners. Please read our terms of use and privacy policy.
Back to Excel Homepage Excel VBA - Reference Guide
VBA Keyword: InuptBox, ActiveCell,
Menu
An Input Box (InputBox) is a function that allows the user to enter a value into a dialog box. The
Recording macros result of an Input Box is stored normally to a variable and remebered for later use in a procedure.
Looking at the code Note that the result of an Input Box is always returns a String value.
Example code snippets In most cases, the following code should be added immediately after the InputBox function call:
Userform input example
If [Variable] = Empty Then Exit Sub
The above piece of code will terminate the procedure if the String variable is empty.
So the the previous example would look like:
Sub Box2()
Dim strResult As String
strResult = InputBox(prompt:="Please enter amount", _
Title:="Data Entry")
If strResult = Empty Then Exit Sub 'Terminates here if empty
ActiveCell.Value = strResult
End Sub
While a the InputBox function s being displayed, the macro procedure is paused waiting for the user
to click a button.
Want to teach yourself Access? Free online guide at About Access Databases
Menu
An Excel Input Box (InputBox) function is different from a VBA Input Box because you can specify
Recording macros what you would like the result of the Input Box to be. If the Type argument is omitted, the Input Box
Looking at the code will return at text (String) value.
If you wish the Input Box to accept both text and numbers, set the Type argument to 1 + 2.
Other links
While a the Excel InputBox function s being displayed, the macro procedure is paused waiting for the
user to click a button.
Want to teach yourself Access? Free online guide at About Access Databases
All trademarks are copyrighted by their respective owners. Please read our terms of use and privacy policy.
Back to Excel Homepage Excel VBA - Reference Guide
Tip: Revert to the Select Case
Menu
(If...Then...Else...End If) VBA Keywords: ActiveCell, Font,
Bold, Italic, Underline, Color,
Recording macros
ClearFormats, InputBox IsNumeric
Looking at the code This is one of the 'control flows' VBA provides which is required to make your VBA code procedures and Exit Sub.
more flexible, reduce the amount of code required and make the system think for itself!
Ways of running macros
Without any of these 'control flows', your code is very linear and rigid which never is really suitable
Where macros are stored when trying to mimic 'real world' processes.
Reasons to write macros
Writing macros The four 'control flows' are:
Procedure types
1. If...Then...Else...End If
Visual Basic editor (VBE)
2. Select Case...End Select
Rules & conventions
3. Do...Until/While...Loop
Excel objects
4. For...Counter/Each...Next
Range/Selection objects
Object hierarchy
Object browser
If Statement
Chart objects
Pivot Table objects This is the logical (conditional test) statement that runs code the yields either a True or False value.
Formulas
Visual Basic Functions There are four flavours of the If I have referred to help understand how this structure is implemented
Creating Add-Ins in VBA:
Variables & constants
Object variables 1. 'One Line' If
Arrays 2. 'True' If
Collections 3. 'Standard' If
Message Box 4. 'Multiple/Nested' If
VBA Input Box
Excel Input Box A logical test can be a value, expression, function or an object property that returns a True or False
Making decisions (If) value using the logical operators <, >, <=, >=, =, <>, Not
(see Formulas).
Making decisions (Case)
Looping (Do...Loop)
One Liner If
Looping (For...Loop)
With...End With blocks
As its name suggests, it's all on one line and requires no End If block.
User defined functions
Event handling
Structure (syntax):
Error handling
If Condition [= True] Then Execute code if true
Debugging
Creating User Forms
It is used as a quick way to add an extra single calling command or calling an additional procedure if
DAO/ADO Objects the condition is true.
Input/Output Files
I use it as a test to see if the procedure should continue and if not to terminate here.
Other links Sub OneLinerIfTest()
Example code snippets Dim strResult As String
strResult = InputBox(prompt:="Please enter amount", _
Userform input example
Title:="Data Entry")
If strResult = Empty Then Exit Sub 'Terminates here if empty
End Sub
True If
This is used in include extra code if true but is used in an If block so that multiple lines of code can
be applied here.
Structure (syntax):
If Condition [= True] Then
Execute multiple lines of code if true
.....
End If
Sub TrueIfTest()
End If
End Sub
Standard If
This is more common type of If block as it provides a True and False option and will therefore
(logically) choose one procedure to call/run.
This can be compared to the more familiar If function in Excel where users specify a True and False
returning value.
Structure (syntax):
If Condition [= True] Then
Execute multiple lines of code if true
.....
Else
Execute multiple lines of code if false
.....
End IF
Sub StandardIfTest()
Else 'FALSE
ActiveCell.Font.Italic = True
ActiveCell.Font.Color = vbRed
End If
End Sub
The Else keyword is the new addition and acts as the False (the catch) should the true fail.
Multiple/Nested If
What about have more than one set of true conditions with a false (as a catch)?
Nested or multiple If's can be as many as required and run in order of their logical conditions.
Structure (syntax):
If Condition 1 [= True] Then
Execute multiple lines of code if true (1)
.....
ElseIf Condition 2 [= True] Then
Execute multiple lines of code if true (2)
.....
ElseIf Condition N [= True] Then
Execute multiple lines of code if true (N)
.....
Else
Execute multiple lines of code if false
.....
End If
Sub MultipleIfTest()
End If
End Sub
The first condition is tested and if True stops and runs code in that block. If the first condition is False
then the second If test condition is tested. Therefore, the second condition is only executed if the first
condition failed.
You can use the ElseIf keyword as many times for each separate new condition but if you intend to
have more than five different conditions then switching to the Select Case statement is the better
practice as it's quicker and cleaner to write.
Else 'FALSE
ActiveCell.Font.Italic = True
ActiveCell.Font.Color = vbRed
End If
End Sub
Want to teach yourself Access? Free online guide at About Access Databases
End Select
Case Value is the value being test logically against the Grade or Expression for a true match. It
continues down the list in order until it finds a true match with a catch using Case Else as the false
option.
Sub SelectCaseExample()
'Code runs here first before it enters the Select Case block...
Select Case ActiveCell.Value
End Sub
It sits all within the Select Case block using the End Select to terminate the logical test
environment.
Note the keyword To meaning a range (the And operator) which is much easier to write as a
condition. Also, using the , (comma) which acts as the Or operator only enhances the way you can
use this statement quickly.
Want to teach yourself Access? Free online guide at About Access Databases
All trademarks are copyrighted by their respective owners. Please read our terms of use and privacy policy.
Back to Excel Homepage Excel VBA - Reference Guide
Tip: Use an Exit Do to terminate a
Menu
(Do...Until/While...Loop) To break a loop during running your
code use CTRL + PAUSE/BREAK.
Recording macros
Looking at the code This is one of the 'control flows' VBA provides which is required to make your VBA code procedures Save your work before running a
more flexible, reduce the amount of code required and make the system think for itself! looping piece of code!
Ways of running macros
Without any of these 'control flows', your code is very linear and rigid which never is really suitable VBA Keywords: ActiveCell, Offset,
Where macros are stored when trying to mimic 'real world' processes. MsgBox and Exit Do..
Reasons to write macros
Writing macros The four 'control flows' are:
Procedure types
1. If...Then...Else...End If
Visual Basic editor (VBE)
2. Select Case...End Select
Rules & conventions
3. Do...Until/While...Loop
Excel objects
4. For...Counter/Each...Next
Range/Selection objects
Object hierarchy
Object browser
Do...Until/While...Loop
Chart objects
Pivot Table objects A Do...Loop is used when you wish to repeat a piece of code a number of times.
Formulas This type of loop works by using a logical test to determine if the loop should repeat or terminate and
Visual Basic Functions move onto the next calling procedure.
Creating Add-Ins
Variables & constants There four variations that can be used and they all have slight differences:
Object variables Structure (syntax):
Arrays UNTIL Keyword
Collections Do
Message Box
Code executed here...
VBA Input Box
....
Excel Input Box
[Exit Do]
Making decisions (If)
Making decisions (Case)
Loop Until Condition [= True]
Looping (Do...Loop)
Looping (For...Loop)
Do Until Condition [= True]
With...End With blocks
User defined functions Code executed here...
Event handling ....
Error handling [Exit Do]
Debugging
Creating User Forms Loop
DAO/ADO Objects
Input/Output Files WHILE Keyword
Do
Other links
Code executed here...
Example code snippets
....
Userform input example
[Exit Do]
Loop
Whichever keyword structure (UNTIL or WHILE) you use is a personal choice as there is no difference
in performance or structure; one is the logical inverse of the other.
You can loop While a condition is True/False or Until a condition is True/False - it's a simple
choice and hopefully the following two examples can make it very clear:
Sub WhileConditionLoop()
Do
End Sub
The above will run and repeat a message box function while the user has chosen 'Yes' to keep the
loop going.
Or putting it another way, until the user chooses the 'No' option.
Sub UntilConditionLoop()
Do
End Sub
Both the above examples displays a message box and will respond in the same way.
Notice the other two variations being very similar other than where the condition is. It's tested first and
not at the end of the loop block. In practical terms, a structure which tests a condition may never run
the code in the block if the condition is not satisfied.
Therefore, the question is "Do you want the procedure to run at least once or potentially not at all?"
This answer is where you place the condition at the beginning or the end of the loop structure.
The next example, will test a condition before running the code in the block based on if the
ActiveCell is empty or not before moving down to the next row.
Sub PositionCursor()
End Sub
If the ActiveCell was blank before entering the loop, why would you need to move the cursor down
a row? Which is why it is tested first and not at the end of the loop block.
Exit Do
Exit Do keywords are included in a block should you wish to terminate a loop block early without
having wait to the end of iteration period.
It can speed up your procedure if there are various tests in a loop that may unexpectedly change state
and act as a catch (error handler of some kind).
Do...Loop - no condition!!
Make sure you have a condition set in any loop block otherwise it will loop infinitely until it runs out of
memory or an object fails.
Do
'Code here...
Loop
End Sub
Want to teach yourself Access? Free online guide at About Access Databases
Menu
(For...Counter/Each...Loop) To break a loop during running your
code use CTRL + PAUSE/BREAK.
Recording macros
Looking at the code This is one of the 'control flows' VBA provides which is required to make your VBA code procedures Save your work before running a
more flexible, reduce the amount of code required and make the system think for itself! looping piece of code!
Ways of running macros
Without any of these 'control flows', your code is very linear and rigid which never is really suitable VBA Keywords: ActiveCell, Offset,
Where macros are stored when trying to mimic 'real world' processes. MsgBox, ActiveWorkbook,
Reasons to write macros Worksheets, WorkBooks, InputBox,
Close and Exit For.
Writing macros The four 'control flows' are:
Procedure types
1. If...Then...Else...End If
Visual Basic editor (VBE)
2. Select Case...End Select
Rules & conventions
3. Do...Until/While...Loop
Excel objects
4. For...Counter/Each...Next
Range/Selection objects
Object hierarchy There two variations of this type of loop both which are controlled counting loops which is neither
Object browser driven by the user or the system.
Chart objects
Pivot Table objects There are:
Formulas 1. For...Counter...Loop
Visual Basic Functions 2. For...Each...Loop
Creating Add-Ins
Variables & constants Before any of the above loops are called, we know how many times the system will repeat the code
Object variables inside the block as opposed to a conditional type loop (Do...Until/While...Loop).
Arrays
Collections For...Counter...Loop
Message Box
VBA Input Box This type of loop is defined by the user telling the system how many times to repeat or the system
using an object method or function to identify the number of iterations.
Excel Input Box
Making decisions (If)
Structure (syntax):
Making decisions (Case)
For Counter = Start To End [Step N]
Looping (Do...Loop)
Looping (For...Loop) Code executed here...
With...End With blocks ....
User defined functions [Exit For]
Event handling
Error handling Next [Counter]
Debugging
Creating User Forms The Counter is a variable keeping count of the current number using the Start and End as its range.
DAO/ADO Objects As soon as the Counter = End then the loop is finished and the code jumps out of the block.
Input/Output Files
Example:
Other links
The following example will display an input box requesting the sales figure for Month 1, Month 2 etc
and input the results into the relevant cell on the spreadsheet. The procedure will therefore loop 12
times.
Sub MonthsForLoop()
Dim MonthlySales As String
Dim num As Integer
For num = 1 To 12
MonthlySales = InputBox("Enter sales for Month " & num)
ActiveCell.Value = MonthlySales
ActiveCell.Offset(1, 0).Select
Next num
End Sub
The InputBox Function is not a practical solution for the above example but it displays how the
For...Loop works.
The Counter variable at the end of the loop (after the Next keyword) is optional and can be left out
but personally it makes it very clear to what is incremented (in the example by 1).
The Step argument is optional too and by default means the variable (Counter) will increment by 1. If
your want to change the increment or use the decrement action (downward count) then you need to
add the Step keyword with the value you wish to increment or decrement.
For example:
'Positive increment of 10
Sub ForLoopStepPositive()
Dim counter As Integer
For counter = 10 To 100 Step 10
MsgBox counter
Next counter
End Sub
'Negative decrement of 10
Sub ForLoopStepPositive()
Dim counter As Integer
For counter = 100 To 10 Step -10
MsgBox counter
Next counter
End Sub
You will also need to make sure the range Start To End is synchronised with the direction of the
Step value otherwise it will cause an error.
For...Each...Loop
This type of loop is a self-counting loop based on a array variable (which use an index), Collections
(which is Excel array to their objects) or by an object member method (like the Count method).
This is commonly used with Collections and therefore the number of times a loop occurs is driven by
the current collection array.
Structure (syntax):
For Each Element In Group
Code executed here...
....
[Exit For]
Next [Element]
A typical example could be to loop through the current number of Worksheets in the ActiveWorkbook:
'Loops through each worksheet in the ActiveWorkbook
Sub HowManySheets()
Dim item As Worksheet
For Each item In ActiveWorkbook.Worksheets
MsgBox item.Name
Next item
End Sub
If there are 5 worksheets in the ActiveWorkbook, the procedure would loop 5 times.
It uses the ActiveWorkbook.Worksheets Collection to determine the number if elements (note the
word is plural) in the group. The Item variable is its element which needs to be the singular matching
object which is in this case Worksheet (singular keyword).
Exit For
Exit For keywords are included in a block should you wish to terminate a loop block early without
having wait to the end of iteration period.
It can speed up your procedure if there are various tests in a loop that may unexpectedly change state
and act as a catch (error handler of some kind).
Want to teach yourself Access? Free online guide at About Access Databases
All trademarks are copyrighted by their respective owners. Please read our terms of use and privacy policy.
Back to Excel Homepage Excel VBA - Reference Guide
VBA Keywords: Selection, Name,
Menu
The WithEnd With block instruction enables you to perform multiple operations on a single object.
Recording macros This is another way to make the code execute more quickly and code styles more efficient.
Looking at the code
Ways of running macros The following procedure will format the selected cells with the font Times New Roman, font size 12,
Where macros are stored Bold, Italic and the colour Blue.
Other links
All trademarks are copyrighted by their respective owners. Please read our terms of use and privacy policy.
Back to Excel Homepage Excel VBA - Reference Guide
VBA Keyword: Function...End
Application.NameofFunction(Arguments Required)
An example which incorporates the Excel Round function to the above user defined function
(ConvertToMiles).
Function ConverToMiles(KM)
ConvertToMiles = Applications.Round(KM / 1.6, 0)
End Function
The above amended code rounds the resulting returning value to zero decimal places using the
standard Excel built-in Round function.
The Optional keyword preceding the argument name flags the argument as an optional
parameter to the function call.
A lot of built-in Excel functions have optional arguments which always follow on from the mandatory
arguments listed in a function and can therefore be omitted defaulting to a value the function
procedure knows how to handle if left out.
This makes function more flexible and can give different returning values (answers) and/or change
the behaviour of how the function will run. Think of the VLOOKUP function in Excel, see it's syntax
below:
The last argument (wrapped in square brackets) is optional and always appears after all mandatory
arguments (3 in this example) which can be omitted and still work. The optional argument is a value of
either True or False which defaults to True if omitted and simply changes the way how this
function will calculate.
An example - following on from the above code snippet above, I want a second argument (as
optional) which allows the user to choose a positive whole number (Byte data type) as its value to
represent the number of decimal places to pass into the calculation. If omitted, it defaults to 0 decimal
places round to the nearest whole number:
The user can now either omit the second argument (cell B2), add a value of 0 to represent no decimal
places (cell B3) or add a positive number to pass into the Excel Round function (cell B4).
Optionally, the As Type keywords can be included to define a certain data type the argument and/or
the function is controlled.
If omitted it will default to Variant (any data type it inherits) and can be open to abuse and more
importantly errors.
You define a data type (see Variables & constants for more information) for each argument in the
function and for the function's returning value too. If left out, you will need to add more code to handle
different data input scenarios.
Let's take a look at what happens if the last above example function is abused.
In cell B3, setting the optional second argument to a String value "ABC" causes the #VALUE! error
(a non numeric data input).
In cell B4, setting the optional second argument to a negative number causes another error #NUM!
even though it's a number but the argument data type Byte only accepts positive numbers between 0
and 255 as its range.
The whole function is also expected to return a number which can be a larger than 255 and we
therefore could apply the Integer as it's returning data type.
Notice I have left out the argument KM data type which defaults to Variant. Personally, I prefer to
test for a data type in the code itself when the user or system passes a value to calculate.
An example:
Function ConvertToMiles(KM, Optional DecPlaces As Byte) As Integer
If IsNumeric(KM) Then
If DecPlaces < 0 Then
ConvertToMiles = KM / 1.6
Else
ConvertToMiles = Application.Round(KM / 1.6, DecPlaces)
End If
Else
ConvertToMiles = 0 'If it fails return a 0
End If
End Function
I have tested to see if KM argument is a number by using the IsNumeric VB function.
All user defined functions can be called in Excel (as explained above) or into a calling Sub procedure
like a VB or Excel function.
Want to teach yourself Access? Free online guide at About Access Databases
All trademarks are copyrighted by their respective owners. Please read our terms of use and privacy policy.
Back to Excel Homepage Excel VBA - Reference Guide
VBA Keyword: InuptBox, MsgBox,
Other links
Note: Private means that the procedure wont appear in the Run Procedure dialog box (i.e. Macros dialog). See
Scope & Visibility in Variables & Constants for information.
Example:
Call the signature Private Sub Workbook_Activate() using the same methods as
previously explained above.
Now the window will always maximise when the workbook gets the focus.
Note: Deleting an event (the signature) will not harm the system as it is re-generated each time you call one of
the pre-defined signatures.
Example:
Using the Private Sub Workbook_SheetActivate(ByVal Sh As Object)signature is
triggered across any worksheet in the active workbook.
The 'Sh' argument can also be used to refer to which worksheet is being called should you wish to
control the index or name of a particular worksheet or group of worksheets.
By including a code line: If Sh.Name = Sheet3 Then... it will handle the logic and
control flow for 'Sheet3'.
Worksheet Events
Example:
Every time the user clicks on 'Sheet1' if the first cell (A1) is empty then prompt the user with an
InputBox function to enter a title.
Note: If there are events at both the worksheet and workbook level which point to the same object
(worksheet), then it's the worksheet level will run first followed by the workbook event.
Other Events
There are other ways to get Excel to trigger a macro using other events from other objects or controls.
It is possible to attach procedures to the ActiveX Controls so that whenever the user clicks onto a
control, the procedure will run.
Example:
When the user clicks on the Command Button, a message box will appear.
1. From Excel, click on the Developer tab (Ribbon Bar), select Insert icon
and choose Button icon from the Form Control section.
2. Draw the Command Button onto the spreadsheet.
3. The Assign Macro dialog box appears, Click the New... button.
4. Enter the following code:
Sub Button37_Click()
MsgBox "Button click event!"
End Sub
Any control drawn on a worksheet or user form will have pre-defined events that can be coded to
respond by the system.
How do you think features like conditional formatting and data validation work in a worksheet when
set in Excel? When the user enters a value in a cell, the Change event is triggered:
Want to teach yourself Access? Free online guide at About Access Databases
All trademarks are copyrighted by their respective owners. Please read our terms of use and privacy policy.
Back to Excel Homepage Excel VBA - Reference Guide
Tip: Save you work before running
Menu
No matter how thorough you are when writing code, errors can and will happen. VBA Keywords: On Error GoTo,
Recording macros There are steps that developers can take to help reduce unwanted errors and this is considered just MsgBox, InputBox, CInt, Dim,
Looking at the code as important as the actual process of the procedure. Resume, Resume Next, Round,
If...Then...Else.
Ways of running macros Before understanding and applying error-handling routines, planning to avoid errors should be
Where macros are stored undertaken.
Visual Basic editor (VBE) Using the Option Explicit statement declaring your variables officially.
Rules & conventions Syntax checking user defined commands and functions.
Excel objects
Comments remarking your code at various points.
Range/Selection objects
Object hierarchy Testing application functional and usability.
Object browser
Note: Some of the above points are methodologies which are outside the scope of this reference guide.
Chart objects
Pivot Table objects
There are three different types of errors:
Formulas
1. Design Time Errors
Visual Basic Functions
2. Run Time Errors
Creating Add-Ins
3. Logical Errors
Variables & constants
Object variables
The order of the above progressively is harder to find leaving the last item the most challenging!
Arrays
Collections
Design Time Errors
Message Box
VBA Input Box The simplest form of error and often caused by typing (typo's) mistakes.
Excel Input Box When typing a known keyword or statement, VBA will turn the text to red (default colour) and if the
Making decisions (If) option is enabled, provide a prompt:
Making decisions (Case)
Looping (Do...Loop)
Looping (For...Loop)
With...End With blocks
User defined functions
Event handling
Error handling
Debugging
Creating User Forms
DAO/ADO Objects
To switch off the above prompt, go to Tools select Options and deselect Auto Syntax Check
Input/Output Files option.
Other links
When executing code, no matter how thorough the debugging process has been, code may
encounter errors while running.
There is only one way of doing this - On Error GoTo instruction. It is not a very sophisticated function,
but it allows the flow of the code to continue and also where applicable, prevent infinite loops (when
the computer keeps on calculating never coming to an end).
Three variations are available:
1. On Error GoTo LabelName
2. On Error Resume Next
3. On Error GoTo 0
On Error GoTo LabelName branches to the portion of the code with the label LabelName
(LabelName must be a text string and not a value).
These commands are usually placed at the beginning of the procedure and when the error occurs,
the macro will branch to another part of the procedure and continue executing code or end,
depending on the instruction given.
'Simple Error handler with Err Object
Sub ErrorTestOne()
On Error GoTo myHandler
myHandler:
MsgBox "Error Number: " & Err.Number & vbNewLine _
& "Description: " & Err.Description
End Sub
The above procedure will cause an error when executed and users will see:
myHandler is a user defined label (must not use known keywords) which listens for any errors that
may occur. When an error is detected, the procedure jumps to a bookmark of the same label with a
colon ( : ) (myHandler:) and executes from that point forward.
Using the Err object, developers can return two common properties Number and
Description. The example message box concatenates these two properties into a user-friendly
message (see above).
It is important to include the Exit Sub statement prior to the bookmark label otherwise the
procedure will execute to the very end of the sub routine and should only be executed when an error
has genuinely occurred.
The error above was due to a type mismatch. In other words I declared a variable intDay as an
integer and assigned a string value to it.
Another example:
'Error to handle incorrect InpuBox value.
Sub ErrorTestTwo()
On Error GoTo myHandler
myHandler:
intInput = 0
blnErr = True
Resume Next
End Sub
The above example illustrates how to gracefully handle incorrect (type mismatched) values and then
resume the next line of execution using Resume Next statement.
The variable blnErr is flagged as true if an error occurs which is then tested with an If statement.
If the Resume Next is replaced with just the Resume statement, you will find the input box will loop
itself until the correct data is entered. Be careful before testing this out due to infinite loops that may
occur (if you edit the wrong part of the procedure).
The statement On Error GoTo 0 (zero) simply disables the error command during the procedure.
Should users wish to switch off this feature? To switch it back on, just introduce a new statement line
of either:
Any code can be written to handle errors gracefully which can include If and Case statements. It is
common to have a Case statement to test which error was fired and deal with it in a separate calling
procedure (branch out another procedure).
Logical Errors
This type of error is the most difficult to trace as its syntax is correct and it runs without any run time
errors.
A logical error is one that does not give users any indication that an error has occurred due to the fact
that a logical error is the process of logic and not the code itself.
Performing a calculation in a spreadsheet using a function will return an answer but is it the correct
answer?
Example:
'Logical Error Test Example
Sub LogicalErrorTest()
Dim lngQty As Long
Dim dblNet As Double
Dim sngDiscount As Single
lngQty = 10
dblUPrice = 250
sngDiscount = 0.15
'Logically CORRECT!
MsgBox Round(((lngQty * dblUPrice) * (1 - sngDiscount)))
End Sub
The above procedure showed a quantity (intQty) of goods, with a unit price (dblUPrice), a
discount (sngDiscount) at a fixed vat rate of 17.5%.
To calculate the correct gross value, there is an order of which operands are calculated (see
Formulas) first and without the care of using brackets, the system follows the rules of mathematics and
looks at the operators precedence automatically.
WRONG!
Followed by the second message box:
CORRECT!
Both calculations worked but the first was illogical to the objective of the process (workflow).
Want to teach yourself Access? Free online guide at About Access Databases
All trademarks are copyrighted by their respective owners. Please read our terms of use and privacy policy.
Back to Excel Homepage Excel VBA - Reference Guide
Tip: Keyboard shortcuts are quick
Other links
At this point, users can either continue to run the remaining procedure (press F5 key) or step through
line by line by pressing the F8 key.
By placing the mouse pointer over any variable or object property, the user will, after a few seconds,
see the current value assigned.
Alternatively, by revealing the Locals Window (button 9 above), users can see all variables and
propertys values:
Debugging between calling procedures can be controlled as the F8 key steps in order line by line
across more than one procedure.
To step out of a sub procedure and carry on with the main procedure, press the SHIFT + F8 keys.
Debug.Print Command
A return value will be printed to the Immediate Window (button 10 above or CTRL + G).
Two ways to print an output value in the immediate window:
1. Debug.Print Expression
2. ? Expression (within the Immediate Window)
Sub CalcPay()
On Error GoTo HandleError
Dim hours
Dim hourlyPay
Dim payPerWeek
hours = InputBox("Please enter number of hours worked", _
" Hours Worked")
End Sub
The above will print the hours variable to the immediate window:
If you set a breakpoint and have the Immediate Window visible, you can use a different method to
reveal the current values of any known variable or property:
Type a question mark ( ? ) followed by a space and then the variable or property and press the enter
key to reveal the output value.
Want to teach yourself Access? Free online guide at About Access Databases
All trademarks are copyrighted by their respective owners. Please read our terms of use and privacy policy.
Back to Excel Homepage Excel VBA - Reference Guide
Tip: Press the F5 function key to run
Menu
Pre-defined Dialog Boxes like InputBox and MsgBox functions are useful and quick to use. However, VBA Keywords: Show,
Recording macros designing your own Dialog Boxes (or User Form), allows you to add other controls and personalise If...Then...Else, MsgBox, RGB &
Looking at the code your application. Unload.
Other links
This toolbar is only available for designing and arranging objects when creating or modifying forms
(user forms).
1 Bring to Front moves the selected object to the front of all other objects.
2 Send to Back moves the selected object to the back of all other objects.
Alignments (Button 5)
Sizes (Button 7)
Toolbox Toolbar
A1 Select Objects: When there is no control to draw, this mode allows you to select
other controls.
A2 Label: Allows you to create text (caption) that a user does not change.
A3 TextBox: Allows you to create an edit box which a user types into.
A4 ComboBox: Allows the user to select from a drop down box items predefined.
A5 ListBox: As above but shows many item in one view with a vertical scroll bar.
A6 CheckBox: Allows the user to create a CheckBox where an item can only have a
yes or no (true or false) answer.
B1 OptionButton: Allows you to display multiple options with a frame where only one
can be selected at a time.
B2 ToggleButton: Like a CheckBox, but a button version.
B3 Frame: Allows you to create a frame to store controls in one group (usually option
buttons).
B4 CommandButton: Creates a button like the OK, Cancel and Other... Buttons.
B5 TabStrip: Allows you to create multiple pages of the same Dialog Box controls.
B6 MultiPage: Allows you to create multiple pages of different controls (multi- tab
Dialog Boxes).
C1 ScrollBar: Provides a graphical scroll bar to allow scrolling through a list of
values.
C2 SpinButton: This button allows you to set values by scrolling up or down through
ranges.
C3 Image: Allows the user to store graphics in a Dialog Box.
C4 RefEdit: Allows a range to be plotted into this control from a spreadsheet.
(Not available in Excel 97).
Common Controls
There are many more controls than the standard set which is installed with Microsoft Excel and can be
added. Select Tools, Additional Controls....
Tick the required item and choose the OK Button. This updates the Toolbox toolbar.
If a single user form needs to handle a large number of controls that can be sorted into categories,
use a Tab Control.
Tab pages can be added and deleted using the properties of the tab (itself) of the control itself by
right-mouse clicking the item.
Setting Controls with Properties (Design Time)
Some controls are better set during the design side of a user form by using the Properties window.
Typical examples of setting these controls:
Setting the default values to edit boxes, checkboxes and many more.
Other colours and graphics that really do not need code handling.
Some controls (some included as above) can be set as the userform is running or before the form is
displayed by setting properties with code.
Typical examples of setting controls with code:
Exiting a control.
Example:
Sub MyDialogBox_Initialize()
TextBox1.Text = "Sales"
Checkbox1.Enabled = True
Me.Command1.SetFocus
OptionCommand1.Visible = False
Checkbox2.Value = False
End Sub
Five controls are set when the form (MyDialogBox) is shown (Initialised).
Displaying a Userform
Once the userform has been created, the next stage is to test to see how the user form will look. You
can use the Run (F5 function key in design time mode) command when the active form is displayed.
But, writing code is ultimately how a user form will be used.
Decide where the code is to be stored (in a Module, Worksheet or Workbook).
Use the name of the form with the Show method command.
Example:
Sub DisplayMyUserform()
MyUserForm.Show
End Sub
The user form is known, as MyUserForm and the Show method will display the user form.
There is one optional argument called Modal which can be explicitly defined and has a value of 0 or
1.
1 = a modal state which means that users have to complete the form and can not click anywhere else
(in the background).
0 = a modeless state which allows users to click outside the form area.
MyUserForm.Show 0
MyUserForm.Show 1 or MyUserForm.Show
Each control will have its own set of events. These events store the code and are executed when that
event is triggered.
For example, a Button recognises the Click_Event, a Form recognises an Intitialize_Event and a
Combo Box recognises a Change_Event.
To assign code to a control, display the form and double click on that control. This opens the module
and the main event allowing code to be written:
Example:
When the OK Button is clicked...
Private Sub cmdOK_Click()
Range("NameResult").Select
EnterText.Hide
If txtName.Text = "" Then
MsgBox "Must enter a name. Try again."
EnterText.Show
End If
ActiveCell.Value = txtName
Unload Me
End Sub
When the userform is displayed, if the OK Button is clicked, the above code is executed and checks to
see if this Textbox (txtName) is empty or not using the If statement. If false, it displays a message
prompt and shows the user form again. If true, it enters the data into a spreadsheet (range -
NameResult).
The Me Property
The Me property returns a reference of the form itself that the code is currently running. This is used
as shorthand for the full reference of a form.
Example:
Suppose you have the following procedure in a module:
Sub ChangeFormColour(FormName As Form)
FormName.BackColor = RGB(Rnd * 256, Rnd * 256, Rnd * 256)
End Sub
You can call this procedure and pass the current instance of the Form as an argument using the
following statement:
Sub cmdColour_Click()
ChangeFormColour Me
End Sub
The ChangeFormColour procedure is passed to the Me property in the current form running which
therefore changes the colour of a specified control(s) to the colour defined.
RGB(Rnd * 256, Rnd * 256, Rnd * 256) is a Red, Green and Blue colour function.
Want to teach yourself Access? Free online guide at About Access Databases
Other links Note: In order to test this section, users will need an Access database and will need to familiarise themselves with
the database. It is not essential to have Microsoft Access loaded as this reference uses the backdoor but it will be
Example code snippets difficult to check the database without it!
Userform input example
Set db = OpenDatabase("C:\db1.mdb")
Set rst = db.OpenRecordset("Customers")
The property Fields of the RecordSet object is a collection (or array) that is held in memory and
by changing the element number, users can return a different field (column of the table).
rst.Fields(1)
The above illustration would show the customers name instead of the ID number.
A good discipline is to close and set an object to Nothing that releases memory, hence the last four
lines of code.
Set db = OpenDatabase("C:\db1.mdb")
Set rst = db.OpenRecordset("Customers")
The above example once again opens the table Customers. Using a conditional loop at which point
the property EOF (End Of File) returns True or False every time the record changes using the
MoveNext method, three columns in the worksheet from the starting active cell are populated by
three different field indexes.
Even though the above example used rst.Fields(8) to determine the ninth column, it may be
fair to say that users may not know the position number of the field but instead know its fieldname. In
this case, users can refer to the name of the field as a string argument.
rst.Fields(Post Code).
Note: Be careful to include a command to increment the collection (MoveNext method) otherwise
this would cause the procedure to loop infinitely or run out of worksheet rows firing an error. Save
your work first before testing the above.
When interrogating a table in a database, it may be required to test to see if the table actually has
records in it before iterating through each record.
Set db = OpenDatabase("C:\db1.mdb")
Set rst = db.OpenRecordset("Customers")
rst.AddNew
rst.Fields("Customer ID") = "XYZ"
rst.Fields("Company Name") = "XYZ Foods Ltd"
rst.Fields("Post Code") = "NW1 8PY"
rst.Update
Note: Be careful to consider the tables structure and database rules that are often implemented
such as primary keys and foreign indexes. The above example would fail if the customer id field
was a unique primary key and the table already had such a reference.
Further coding would be required to test to see if the record number existed, before adding and
updating the record.
To edit a record, users must first locate the record (if it can be found) and then use the Edit method.
rst.Edit
rst.Fields("Customer ID") = "XYZ"
rst.Fields("Company Name") = "XYZ Foods Ltd"
rst.Fields("Post Code") = "W12 6RF"
rst.Update
Set db = OpenDatabase("C:\db1.mdb")
Set tbl = db.CreateTableDef("Contact Log")
With tbl
.Fields.Append .CreateField("Log ID", dbInteger)
.Fields.Append .CreateField("Date", dbDate)
.Fields.Append .CreateField("Caller", dbText)
.Fields.Append .CreateField("Comment", dbText)
.Fields.Append .CreateField("Completed", dbBoolean)
db.TableDefs.Append tbl
End With
The above example will create a new table Contact Log, create new fields and then bind it to the
new table using db.TableDefs.Append tbl. Next it will add a single record using the correct
data to match the data types as defined in the table.
This procedure will only run once and then cause an error if executed again. This is due to the fact
this database cannot contain duplicate named tables.
Therefore, users need to add error-handling procedures as well as testing to see if the table exists.
To delete a table along with its records, use db.TableDefs.Delete "Contact Log".
Again an error will be fired if the system cannot locate the table (misspelling or already deleted).
There are many properties and methods of DAO which are not covered in this guide. This library
allows many ways to produce the same effect which include writing SQL (structured query language).
ADO
ADO stands for ActiveX Data Objects is an alternative method of connecting to a database.
In order to use this feature, users will need to add the ADO library to the project.
Choose from the Tools menu and select Reference
Note: You may have noticed that there several versions of ActiveX Data Objects in the illustration above.
Generally, you should choose the latest version but depending on which version of Excel (or more accurately
Windows operating system) try and pick the best fit version. For example 2.8 is for those running on Windows XP
where as users would choose 6.0 for Windows Vista.
This library will than allow objects to be created to interrogate a database, tables, fields and return
information to populate a spreadsheet. This will also allow users to add, edit, update and delete data
to an external file without the need to open the associated application.
An advanced feature of this library (ADOX) will even allow users to create, modify and delete
structures of a database whether a table, query, stored procedure or fields.
Using the control flow techniques as discussed in this manual, the user can fully control how data
should be handled - opening the potential power of VBA.
Note: In order to test this section, users will need an Access database and will need to familiarise themselves with
the database. It is not essential to have Microsoft Access loaded as this reference uses the backdoor but it will be
difficult to check the database without it!
Sub ConnectAccessDB()
Dim cn As ADODB.Connection
With cn
.Provider = "Microsoft.Jet.OLEDB.4.0"
.ConnectionString = "Data Source=C:\db2.mdb;"
.Open
End With
End Sub
The above example connects to an Access database (db2).
There other ways to connect as well as setting optional arguments which control the method of
connection (using ODBC or DSN-Less etc) which is beyond this article.
With cn
.Provider = "Microsoft.Jet.OLEDB.4.0"
.ConnectionString = "Data Source=C:\db2.mdb;"
.Open
End With
rs.Close
cn.Close
Set rs = Nothing
Set cn = Nothing
End Sub
The above example creates a connection. It then creates another new object (rs) which the recordset
of a table, query or SQL source and opens it too.
Now you have a collection of data (all records in that file). Using a property (Fields), you can pass
either an index or string name into it to refer to any field in that source file and return one of several
values (in this case the data value).
Make sure you close and dispose of the objects when finished (and in the correct order) though it will
clear and dispose of all objects when the procedure comes to an end - just good habits of
programming!
It is good practice to narrow down the recordset to the smallest amount of data in memory which the
above example fails to do (all records). Instead, consider passing a query or SQL statement instead:
There are optional arguments which also help performance and restrictions to an open connection
which I've used in my example above adOpenKeyset, adLockOptimistic, adCmdTable
and will require further investigation to help establish the rule (refer to VBA help for more information).
rs.Close
cn.Close
Set rs = Nothing
Set cn = Nothing
End Sub
Using the rs.Update property enforces any changes to be saved and written to the database.
If you wish add a new record, you can use rs.AddNew method but it will still need to use
rs.Update to save the changes.
Example:
Sub NewRecord()
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
With cn
.Provider = "Microsoft.Jet.OLEDB.4.0"
.ConnectionString = "Data Source=C:\db2.mdb;"
.Open
End With
rs.Close
cn.Close
Set rs = Nothing
Set cn = Nothing
End Sub
The above example populates new values to four fields and then saves the changes. Make sure any
record being added satisfies the rules of the data source which is being used to store the data which
will include indexing (which is generally a mandatory field).
Other useful methods include EOF (end of file) and BOF (beginning of file) which allows you to iterate
through records using loops. - look at the help for more information.
There is much, much more on this subject (I've not done this justice) and users should now be
confident to go off and investigate further using various other resources (books and the web!).
Want to teach yourself Access? Free online guide at About Access Databases
Menu
VBA already includes commands to allow data to read or write to external text files. This is more
Recording macros commonly known as I/O (Input / Output) and is used to store files in the formats such as txt, csv and
Looking at the code ini files.
Chart objects The above example creates an instance of a file using the FreeFile function, which returns a
unique number (as its handler). The Open method is used to locate and open the file.
Pivot Table objects
The Output property tells the system that data is to be written to the named file using the pointer
Formulas
#fnum.
Visual Basic Functions
The Write method adds line-by-line data to the pointer and then is lost with the Close method.
Creating Add-Ins
Even if the file name does not exist, it will create this file in the specified path but the path must exist.
Variables & constants
If the filename already exists, this routine will overwrite (no prompt) and the previous file will be lost.
Object variables
Arrays
The file generated is a 'txt' file:
Collections
Message Box
VBA Input Box
Excel Input Box
Making decisions (If)
Making decisions (Case)
Looping (Do...Loop)
Looping (For...Loop)
With...End With blocks
User defined functions Example of Input Data:
Event handling Sub ReadTextFile()
Error handling Dim fnum
Dim strField1 As String, strField2 As String
Debugging
Creating User Forms fnum = FreeFile()
Open "C:\vba.txt" For Input As #fnum
DAO/ADO Objects
Input/Output Files Do Until EOF(fnum)
Input #fnum, strField1, strField2
Debug.Print strField1 & " : " & strField2
Other links Loop
Example code snippets
Close #fnum
Userform input example End Sub
The above example uses the Input property instead to change the direction of the flow of data (read
from).
Using the EOF method, the procedure loops through the delimiter line break until it reaches the end of
the file.
To view the results, open the Immediate Window (Ctrl + G) before running the above procedure:
The above two examples demonstrates how to read and write data to and from external files and will
require a little more coding to deal with interaction and variables to make this more flexible (and
practical).
Want to teach yourself Access? Free online guide at About Access Databases
All trademarks are copyrighted by their respective owners. Please read our terms of use and privacy policy.
Back to Excel Homepage Excel VBA - Reference Guide
errorHandler:
MsgBox "Error"
End Sub
Back to top
Back to top
For rowIndex = 1 To 10
For colIndex = 1 To 5
If Cells(rowIndex, colIndex).Value = "X" Then
Cells(rowIndex, colIndex).Value = "O"
Else
Cells(rowIndex, colIndex).Value = "X"
End If
Next colIndex
Next rowIndex
End Sub
Back to top
Back to top
End Sub
To set the visible property to True on all sheets in a workbook.
Sub UnHideAll()
Dim wSh As Worksheet
Back to top
Adds new worksheet with the month and year as its name and sets the range("A1:A5") from Sheet1 to
new worksheet.
This can only be executed once for the same period due to excel not allowing duplicate worksheets
names.
Make sure you have a worksheet called Sheet1 and that its range A1:A5 has some content which to
copy across.
Sub AddSheet()
Dim wSht As Worksheet
Dim shtName As String
Copies the contents of the first positioned worksheet to a new worksheet (NewSheet) validating if
sheet exists first.
Sub CopySheet()
Dim wSht As Worksheet
Dim shtName As String
Dim shtName As String
Index number for a sheet can be used instead of the actual string name. This is useful if name is not
known or you want to control the order position of the sheet in question.
Back to top
Dim hours
Dim hourlyPay
Dim payPerWeek
To split a single line of execution into multiple lines, use the underscore character ( _ ).
What impact will this have if you use the integer function (Int()) instead of the currency functions
(CCur)?
Other functions: CDbl (double) and CSng (single).
Date Entry & Formula with InputBox which prompts the user for the number of times to iterate, creates
heading and calculates gross values with final totals at the end of the columns.
Sub ProcessTransactions()
ActiveCell.Value = "NET"
ActiveCell.Offset(0, 1).Value =
"GROSS" ActiveCell.Offset(1, 0).Select
With Selection.Borders(xlEdgeTop)
.LineStyle = xlContinuous
.Weight = xlThin
.ColorIndex = xlAutomatic
End With
With Selection.Borders(xlEdgeBottom)
.LineStyle = xlDouble
.Weight = xlThick
.ColorIndex = xlAutomatic
End With
End Sub
The above is A For Next Example with InputBox Function, With Block and Offset method
Back to top
Printing examples
To control orientation and defined name range - 1 copy.
Sub PrintReport1()
Sheets(1).PageSetup.Orientation = xlLandscape
Sheets(1).PageSetup.Orientation = xlLandscape
Range("Report").PrintOut Copies:=1
End Sub
To print a defined area, centre horizontally, with 2 rows as titles, in portrait orientation and fitted to
page wide and tall - 1 copy.
Sub PrintReport3()
With Worksheets("Sheet1")
.PageSetup
.CenterHorizontally = True
.PrintArea = "$A$3:$F$15"
.PrintTitleRows = ("$A$1:$A$2")
.Orientation = xlPortrait
.FitToPagesWide = 1
.FitToPagesTall = 1
End With
Worksheets("Sheet1").PrintOut
End Sub
To print preview, control the font and to pull second line of header (A1) from first worksheet.
Sub PrintHeaderPreview()
ActiveSheet.PageSetup.CenterHeader = "&""Arial,Bold Italic""&14 _
My Report" & Chr(13) & Sheets(1).Range("A1")
ActiveWindow.SelectedSheets.PrintPreview
End Sub
"&""Arial,Bold Italic""&14 = fields used in page set-up of header/footer
Back to top
To display the full path and filename of the current workbook (Function)
Sub FormatHeader()
With ThisWorkbook
.Worksheets("MySheet").PageSetup.LeftHeader = .FullName
End With
End Sub
Sub Restore_FKeys()
Application.OnKey "{F3}"
End Sub
Can be assigned to the event of when a workbook opens a closes.
Cursors
Sub ShowHourGlass()
Application.Cursor = xlWait
End Sub
Sub ResetCursor()
Application.Cursor = xlNormal
End Sub
Can also be xlNorthwestArrow and xlIBeam.
With ActiveWindow
.DisplayFormulaBar = Not .DisplayFormulaBar
.DisplayStatusBar = Not .DisplayStatusBar
End With
Back to top
rng = Selection.Address
ActiveSheet.Names.Add Name:="MyRange3", RefersTo:="=" & rng
End Sub
With ws
'Find the last row
LastRow = .Cells.Find(What:="*", _
SearchDirection:=xlPrevious, _
SearchOrder:=xlByRows).Row
'Find the last column
LastCol = .Cells.Find(What:="*", _
SearchDirection:=xlPrevious, _
SearchOrder:=xlByColumns).Column
End With
'Finally, initialize a Range object variable for
'the last populated row.
Back to top
Sub MoveUp()
ActiveCell.Offset(-1, 0).Select
End Sub
Sub MoveRight()
ActiveCell.Offset(0, 1).Select
End Sub
Sub DownLeft()
ActiveCell.Offset(0, -1).Select
End Sub
Sub LastCellInRange()
Range(ActiveCell.Address).End(xlDown).Select
Range(ActiveCell.Address).End(xlToRight).Select
End Sub
Back to top
Age (simple)
Function Age2(DOB)
Age2 = Int((Now() - DOB) / 365.25) & " Years old"
End Function
Age (alternative)
Function Age(DOB)
If Month(DOB) > Month(Now) Then
Age = Year(Now) - Year(DOB) - 1
ElseIf Month(DOB) < Month(Now) Then
Age = Year(Now) - Year(DOB)
ElseIf Day(DOB) <= Day(Now) Then
Age = Year(Now) - Year(DOB)
Else
Age = Year(Now) - Year(DOB) - 1
End If
End Function
Returns the cell in range which is underline (single style) or the word unknown
Public Function GetUnderlinedCell(CellRef As Range) As String
Dim c As Integer
Dim sResult As String
'Assume Unknown
sResult = "Unknown"
'Return Results
GetUnderlinedCell = sResult
End Function
Visual Basic Functions - Choose (Lookup).
Sub LookupExample()
Dim strMonth As String
Dim bytCurMonth As Byte
bytCurMonth = Month(Date)
strMonth = Choose(bytCurMonth, "Jan", "Feb", "Mar", "Apr", _
"May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")
MsgBox "Current month is " & strMonth
End Sub
Also, take a look at the Switch() function using VBA Help.
Back to top
With wdApp
.Visible = True
.WindowState = wdWindowStateMaximize
End With
With mywdRange
.Text = Range("B1") & vbNewLine & "This above text is _
stored in cell 'B1'."
.Font.Name = "Comic Sans MS"
.Font.Size = 12
.Font.ColorIndex = wdGreen
.Bold = True
End With
errorHandler:
Set wdApp = Nothing
Set myDoc = Nothing
Set mywdRange = Nothing
End Sub
Back to top
With objMail
.To = "name@domain.com"
.Subject = "Excel VBA to Outlook Message Example"
.Body = "This is an automated message from Excel. " & _
vbNewLine & "The content of cell reference 'A1' is: " & _
Range("A1").Value
.Display
End With
Back to top
Want to teach yourself Access? Free online guide at About Access Databases
Home | Terms of Use | Privacy Policy | Contact
copyright 2010 TP Development & Consultancy Ltd, All Rights Reserved.
All trademarks are copyrighted by their respective owners. Please read our terms of use and privacy policy.
Back to Excel Homepage Excel VBA - Reference Guide
Where macros are stored Here's what we are are going to achieve:
Reasons to write macros 1. A user form will load from a button on a worksheet.
Writing macros
Procedure types
Visual Basic editor (VBE)
Rules & conventions
Excel objects
Range/Selection objects
Object hierarchy
Object browser
Chart objects
Pivot Table objects
Formulas
Visual Basic Functions 2. Users must complete Firstname, Surname and choose a Department (which will
be coded as mandatory fields).
Creating Add-Ins
3. When choosing the Add button it will append to the worksheet (called Data) and
Variables & constants
always find the next available blank row to populate.
Object variables
4. The form will remain open clearing the values ready for the next record input until
Arrays the Close button is clicked.
Collections 5. A private macro (from the standard module) calls the user form (via its worksheet
Message Box button).
VBA Input Box
Excel Input Box There are properties and code for the form, two and buttons and drop-down combo box which we will
need to add the form's private module.
Making decisions (If)
Making decisions (Case)
The order in creating such a feature should loosely follow these steps:
Looping (Do...Loop)
1. Create the user form canvas.
Looping (For...Loop)
2. Add the controls to the form and set various basic properties (including names).
With...End With blocks
3. Add code to the form's controls
User defined functions
4. Code the interaction to the worksheet (& prepare the worksheet layout too).
Event handling
5. Add a macro to call the form and attach to a button on the worksheet.
Error handling
6. Test the process!
Debugging
Creating User Forms
Create the user form canvas
DAO/ADO Objects
Add a new blank user form the VBA Project.
Input/Output Files
In the VBE Editor, select Insert, UserForm.
Other links
Add the controls to the form
Example code snippets
You need to add the following controls:
Userform input example
1. Two Command Buttons
2. Three Labels
3. Two TextBoxes
4. One ComboBox
5. One CheckBox
Place the controls roughly where you would like to use these control and resize the form.
Don't worry about the exact position for now:
Setting the properties to each control
The following controls can be set using the Properties Window (F4 function key).
First single click to select the control (so it has the focus) and then from the properties changes their
settings.
Here's the table for the above controls (and user form itself):
Control Property Value
CommandButton1 Name cmdAdd
Caption Add
Default True
Height 20
Width 60
Left 132
Top 114
TabIndex 4
You can change some of these properties to taste - this is what I'm using in this example.
Starting with the Close button which will simply close and end the user form.
Private Sub cmdClose_Click()
'close the form (itself)
Unload Me
End Sub
Unload Me refers to itself which is quick and easy. To explicitly close a user form, you refer to actual
name of the form. Therefore, using Unload frmDataInput will be the same outcome.
Next, lets add code (run time) to populate the ComboBox control (cboDept) which will dynamically
create four fixed options to choose from.
Private Sub UserForm_Initialize()
Me.cboDept.AddItem "Finance"
Me.cboDept.AddItem "Sales"
Me.cboDept.AddItem "Markerting"
Me.cboDept.AddItem "Human Resources"
End Sub
As the form loads (initialises), it adds four items to the cboDept control and then positions the cursor
in txtFName ready for the user to start keying in data.
You could of course set this in the properties (RowSource) for cboDept instead which refers to range
of cells in a worksheet.
The final piece of code is attached the cmdAdd button control so when users click this event, it will
add the details to the worksheet (Data).
Private Sub cmdAdd_Click()
Dim i As Integer
'if all the above are false (OK) then carry on.
'check to see the next available blank row start at cell A2...
Do Until ActiveCell.Value = Empty
ActiveCell.Offset(1, 0).Select 'move down 1 row
i = i + 1 'keep a count of the ID for later use
Loop
'Clear down the values ready for the next record entry...
Me.txtFName.Text = Empty
Me.txtSName.Text = Empty
Me.cboDept.Text = Empty
Me.chkManager.Value = False
End Sub
The above should be easy to follow (look at the comments).
We don't have to tell the system which worksheet to be in as it is going to be called from a control
(worksheet button) where the data is held in the same worksheet and then hide this procedure from
the Macros dialog box stopping any other way for this form to be called.
TEST IT OUT!
This is how the form looks as it is called from the worksheet button control from the Data worksheet.
Want to teach yourself Access? Free online guide at About Access Databases