You are on page 1of 16

Excel VBA Reference

Procedural Order..............................................................................................................................2
Open code module for a sheet..........................................................................................................2
Naming a procedure or function......................................................................................................2
Call a procedure...............................................................................................................................2
Specifying a Startup Procedure........................................................................................................3
Call a function..................................................................................................................................3
Working with Controls....................................................................................................................3
Turn off Screen Updating................................................................................................................3
Declaring Variables ........................................................................................................................4
Assigning values to variables:.........................................................................................................4
Declaring Using an Array................................................................................................................4
Select Case Statements....................................................................................................................5
Do While Loop/Do Until Loops......................................................................................................5
For Next Loops................................................................................................................................5
Referring to a combo box value.......................................................................................................6
Setting a combo box value...............................................................................................................6
Add Items to a combo box...............................................................................................................6
Clear a Como Box............................................................................................................................7
Deleting Rows..................................................................................................................................7
Opening a database connection........................................................................................................7
Closing database connection............................................................................................................8
Recordset BOF and EOF.................................................................................................................8
Move to a record in a recordset........................................................................................................8
Copying data directly from a recordset............................................................................................9
Getting values from fields in a recordset.........................................................................................9
Looping through a recordset............................................................................................................9
Message Boxes.................................................................................................................................9
Reference Overview.......................................................................................................................10
Sheet References............................................................................................................................10
Cell References..............................................................................................................................11
Row References.............................................................................................................................11
Range References...........................................................................................................................11
Setting Cell/Range Properties........................................................................................................12
With Statement...............................................................................................................................12
Formatting Lines and Borders.......................................................................................................13
Make Copy of a Sheet....................................................................................................................13
Create New Workbook..................................................................................................................13
Go to Last Cell in Data Range.......................................................................................................14
Parsing a String..............................................................................................................................14
Dynamic Array Variable:...............................................................................................................14
Find Last Non-Empty Row in Sheet..............................................................................................15
Show a User Form.........................................................................................................................15
Locking Cells.................................................................................................................................15

Procedural Order
1. Process any inputs to the subroutine
2. Declare variables
3. Do Stuff, such as:
Declare database connections and recordsets (as needed)
Open database connection and recordset
Process data using Loops, Case statements, etc. (as needed)
Assign values to variables, increment, change, etc.
Output datacopy from recordset, assign cell values, etc.
Show messages, notifications, prompts. etc.
Close connections and recordsets
4. Exit

Open code module for a sheet


Right-click sheet, choose View Code

Naming a procedure or function


Example:
Sub Thingy()
Function Thingy()
Notes: a) there is option to make a sub private (Private Sub X), b) all code goes
between Sub and End Sub

Call a procedure
Note: procedures and functions can be called by another procedure.
Example:
Call Thingy
Call Sheets("Sheet1").Thingy if the Sub belongs to another sheet

Specifying a Startup Procedure


Note: This procedure runs when the sheet is first opened.
Go to code page for This Workbook, then create a procedure called:
Private Sub Workbook_Open()

Call a function
Example:
Call Thingy(variable)
Note: value(s) in parentheses can be used as variables in the called sub/function and dont
have to be dimmed

Working with Controls


Notes: Add custom controls to an Excel sheet such as buttons and combo boxes.
Steps:
a) Enable Controls Toolbar: View|Toolbars|Control Toolbox (note: not forms
toolbox)
b) Set up event-based Subroutine:
Click Design Mode button double click on control automatically
creates change or click subroutine
Common types of event-driven subroutine:
click used for command buttons
change used for changes in combo box values

Turn off Screen Updating


Application.ScreenUpdating = False
Note: eliminates strobe effect and shows hourglass instead.

Declaring Variables
Note: Use Dim to declare, AS to specify data type (a good idea)
Example:
Dim comboval
Dim vSort
Dim intRecordCount As Integer

Assigning values to variables:


Example:
comboval = ComboBox1.Text
vSort = "SupervisorName"
intRowCount = intRowCount + intRecordCount + 1

Declaring Using an Array


Note: Array a type of variable used to store multiple values in a table-like structure,
where values are numbered. A multidimensional array has two + sets of values.
Examples:
Declare static array
Dim MyNames(1 to 10) As String
Declare dynamic array.
Dim MyNames() As String dynamic array, has to be "re-dimmed"
Re dimming an array
ReDim MyNames(1 to Max) Re-dim's when the max value is known
When the max value is not known then you can re-dim as part of a loop
Dim tmp As String, fCount As Integer
fCount = 0
tmp = Dir("*.*")
While tmp <> Empty

fCount = fCount + 1
ReDim Preserve FolderFiles(1 to fCount)
' declares the array variable again (size+1)
FolderFiles(fCount) = tmp
tmp = Dir
Wend
Note that the command preserve is used with ReDim to keep existing data in
the array

Select Case Statements


Use to evaluate a variable and tell program what to do with each possible outcome:
Note on basic syntax: a) Select Caseb) Case this, Case that, repeat until all likely cases
dealt with, c) Case Else--to cover all other cases, d) End Select
Example:
Select Case ComboBox2.Text
Case "% of Goal"
vSort = "Sum(TotalCourseDays)/(Count(EmployeeID)*7)"
Case Else
vSort = "SupervisorName"
End Select

Do While Loop/Do Until Loops


Note: Peforms an operation while a condition is met, or until a condition is met.
Syntax: Do While [condition].[stuff].Loop
Example:
Do Until objRst.EOF
comboval = objRst.Fields.Item("Org")
ComboBox1.AddItem (comboval)
objRst.MoveNext
Loop

For Next Loops


Syntax: For X = 1 to N Next X

Note: a) Will increment X and keep going until X = N, b) the X doesnt have to be
declared.
Example:
For c = 1 To intColCount
.Cells(intRowCount, c).Value = This is Column & c
Next c
Note: another variant on this is For Each, which will loop through all values in a
series:
Example:
For Each Shp In .Shapes
do stuff
Next

Referring to a combo box value


Example:
=ComboBox2.Text
Or
orgVal = Sheets("Summary").ComboBox1.Text
In second case combo box is on a different sheet, so sheet reference needed

Setting a combo box value


Example:
ComboBox1.Value = vMgr

Add Items to a combo box


Syntax: [ComboBoxName].AddItem(Item text)
Examples:

ComboBox1.AddItem(Smithee)
Adding values programmatically:
Do Until objRst.EOF
comboval = objRst.Fields.Item("Org")
ComboBox1.AddItem (comboval)
objRst.MoveNext
Loop

Clear a Como Box


ComboBox1.Clear

Deleting Rows
ActiveSheet.Rows("7:65536").Delete

Opening a database connection


1) First create and name two objects: the connection and the recordset:
Syntax: Set [Object Name] = CreateObject([Object Type])
Example:
Set objConn = CreateObject("ADODB.Connection")
Set objRst = CreateObject("ADODB.Recordset")
2) open the connection:
Syntax: [Name].Open.etc.
Example:
objConn.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & ThisWorkbook.FullName & ";" & _
"Extended Properties=""Excel 8.0;HDR=Yes;"";"
Note: speficy a) provider, b) data sourcefile or ODBC, c) properties
3) Then open the recordset, using a query:

Syntax: [Name].Openetc.
Example:
objRst.Open "SELECT SupervisorName, Sum(ProdServ), Sum(EmpDev),
Sum(Tech), Sum(TotalCourseDays),FROM [TrnDaysSum$] WHERE Org
= '" & comboval & "' GROUP BY SupervisorName ORDER BY " &
vSort, objConn
Note: specify a) the query to be used (in quotes) and b) the connection to be used

Closing database connection


Always do this when done with data
Syntax: a) [Object Name].Close and then b) Set [ObjectName] = Nothing
Example:
objRst.Close
Set objRst = Nothing
objConn.Close
Set objConn = Nothing

Recordset BOF and EOF


Note: BOF = Beginning of recordset, EOF = end
Syntax: [Name].BOF or [Name].EOF
Example:
a) Dealing with empty recordset:
If objRst.BOF = True And objRst.EOF = True Then Exit Function
b) Looping: Do Until objRst.EOF etc.

Move to a record in a recordset


a) move to first: [Name].MoveFirst
b) move to next: [Name].MoveNext used within a Do While or Do Loop statement

Copying data directly from a recordset


Syntax: [Sheet reference],Cells([Cell reference)].CopyFromRecordest [Recordset Name]
Notes:
a) Name the cell starting point
b) Give the name of recordset
Example:
ActiveSheet.Cells(intRowCount, 2).CopyFromRecordset objRst

Getting values from fields in a recordset


Syntax: [RecordsetName].Fields.Item(Name or index number)
Example:
comboval = objRst.Fields.Item("Org")
Note: can use this to assign values to cells or to a variable

Looping through a recordset


Note: first move to the first record in the recordset and then start looping!
Example:
objRst.MoveFirst
Do Until objRst.EOF
intRecordCount = intRecordCount + 1
If objRst.EOF Then Exit Do
objRst.MoveNext
Loop

Message Boxes
Note: Notifies user of information, or prompts user to make a choice

Syntax: MsgBox(Text)
Example (Notification):
MsgBox ("Done!")
Example (Choice):
If MsgBox("Are you sure you want to go through with this?", vbYesNo) = vbNo
Then Exit Sub
End If

Reference Overview
Notes:
Basic Syntax is [Worbook].[Sheet].[Object]
Thus.
[Sheet].Cells
[Sheet].Range
[Sheet].Rows
[Sheet].Columns
After the reference.the relevant methods or properties can be applied.
Syntax: [Sheet].[Object].[Method/Property]
Examples:
.Delete
.Value
.Format
.Formula
Etc.

Sheet References
Syntax: ActiveWorkbook.Sheets(Name or Index)
Or

ActiveSheet to refer to current sheet.


Examples:
ActiveWorkbook.Sheets("ManagerDetail").Select
ActiveWorkbook.Sheets(2).Select
ActiveSheet (refers to currently selected sheet)

Cell References
Syntax: Either numeric or literal address.
Numeric .Cells(row,column)
Literal .Range(literal address)
Examples:
Get value from a cell vMgr = ActiveCell.Value
Assign value to a cell ActiveSheet.Cells(3, 2).Value = "Total"
Or:
ActiveSheet.Range("B3").Value = "Hello World"

Row References
Syntax: ActiveSheet.Rows(reference)
Example:
ActiveSheet.Rows("7:65536").Delete

Range References
Syntax: Range([Cell1], [Cell2])
Or

Range(Cells([row],[col]),Cells([row],[col]))
Examples:
Range("E9", "E200")
Range(Cells(7, 6), Cells(intRowCount, 6))

Setting Cell/Range Properties


Notes: Some common properties
.NumberFormat
.Value
.Formula
.Font.Bold
Examples:
.Range("E9", "E20000").NumberFormat = "m/d/yy;@"
.Cells(intRowCount, 2).Value = "Total"
.Cells(intRowCount, 2).Font.Bold = True
.Cells(intRowCount, 4).Formula = "=SUM(D7:D" & intRowCount & ")"

With Statement
Note: shorthand so that the Worksheet or range part of a reference neednt be repeated for
multiple operations within it.
Syntax: With Sheets([name or number])[stuff]End With
Example:
With Sheets("ManagerDetail")
.Rows("7:65536").Delete
.Range("B3").Value = "Hello World"
End With

Formatting Lines and Borders


Note: Format style, weight, color of cell borders
Syntax. [Range].Borders([Border Type]).[Setting to be formatted] = [format]
Examples:
With ActiveSheet.Range(Cells(7, 6), Cells(intRowCount, 6))
With .Borders(xlEdgeLeft)
.LineStyle = xlContinuous
.Weight = xlThin
.ColorIndex = xlAutomatic
End With
Options for border types are.
xlEdgeLeft, xlEdgeTop, etc.

Make Copy of a Sheet


Notes: Copies specified sheet out to a new workbook
Syntax: Sheets([name or number]).Copy
Example:
Sheets("EmployeeDetail").Copy

Create New Workbook


Example:
Dim Wk As Workbook
Set Wk = Workbooks.Add
Wk.Sheets(1).Name = "Summary"
For x = 1 To 10
Wk.Sheets.Add After:=Sheets(Sheets.Count)
ActiveSheet.Name = "Page" & x

Next x

Go to Last Cell in Data Range


Note: Determine last cell in a range in a case where the range of cells with data might be
variable.
Example:
Range("A1").Select
ActiveCell.SpecialCells(xlLastCell).Select
Example (find last row):
LastRow = Cells.Find(What:="*", After:=[C1], SearchOrder:=xlByRows,
SearchDirection:=xlPrevious).Row

Parsing a String
Note: may want to use this when parsing a field that contains a delimiter--say a case
where a last name is needed from a string containing first and last name separated by a
comma.
Example:
While Cells(rowNum, colNum).Value <> ""
n = InStr(1, Cells(rowNum, colNum).Value, ",")
lastName = Left(Cells(rowNum, colNum).Value, n - 1)
Wk.Sheets.Add After:=Sheets(Sheets.Count)
ActiveSheet.Name = lastName
rowNum = rowNum + 1
Wend

Dynamic Array Variable:


Example:
Dim MyNames() As String ' declares a dynamic array variable
Dim iCount As Integer
Dim Max As Integer
Max = ThisWorkbook.Names.Count ' finds the maximum array size

ReDim MyNames(1 to Max) ' declares the array variable with the necessary
size
For iCount = 1 To Max
MyNames(iCount) = ThisWorkbook.Names(iCount)
Next iCount
Erase MyNames() ' deletes the varible contents, free some memory
End Sub

Find Last Non-Empty Row in Sheet


Syntax:
Use Cells.Find to locate empty cells, have to specify 1) a starting point cell, 2)
search ordercolumns or rows and 3) search direction.
Note:
To search down, use xlPrevious
Example:
LastRow = Cells.Find(What:="*", After:=[A1], SearchOrder:=xlByRows,
SearchDirection:=xlPrevious).Row

Show a User Form


Note:
Shows or hides a user form.
Example:
UserForm1.Show
UserForm1.Hide

Locking Cells
Note:
first have to protect entire sheet
Example:

.Locked = True
.FormulaHidden = True
.Protect DrawingObjects:=True, Contents:=True, Scenarios:=True