Excel VBA Macro Programming
Excel VBA Macro Programming
Programming
Your First Excel VBA Macro
Explicit Declaration
Option Explicit
Scope and Lifetime of Variables
Local Variables
A local variable uses Dim, Static, or ReDim
(arrays only) to declare the variable within a
procedure.
Module-Level Variables
A module-level variable is declared for a
particular module. It is available to all
procedures within that module but not to the
rest of the application.
Scope and Lifetime of Variables
Global Variables
Global variables are declared in the
declarations part of a module with the Global
statement
Example
Global TempVal
Data Types
Arrays
Dim employee1 as String, employee2 as String,.......
Dim employee(25) as String
Multidimensional Arrays
Dim temp(10,4) as String
Dim temp(10,4,3) as String
Dynamic Arrays
Dim temp() LBound(temp)
Example
Const Path_Name = "C:\temp\"
Modules, Functions, and Subroutines
Modules are where you write your code.
Functions and subroutines are the two
different ways of creating a piece of working
code.
The Difference Between Subroutines and Functions
subroutine is different from a function in that it
does not return anything directly and so
cannot be used directly in the spreadsheet
the way a function can.
Public and Private Functions and
Subroutines
keyword Public or Private
Private Sub PrivateSub()
…
End Sub
Argument Data Types
Function (Target as String)
Optional Arguments
Function Myfunction (Target as String,
Optional Flag as Integer)
Passing Arguments by Value
x = 100
z = Adjust(x)
Function Adjust(ByVal Target as Integer)
Programming Basics
Decisions
If..Then..Else
Sub test_if()
If Application.ActiveCell = 5 Then
MsgBox "Cell is 5"
Else
MsgBox "Cell is not 5"
End If
End Sub
Conditional operators
Multiple Conditional Statements
If x = 1 Or y > 5 Then
MsgBox "x=1 or y>5"
End If
Select Case Statements
Sub test_do()
x =0
Do Until x = 100
x =x +1
Loop
MsgBox x
End Sub
Early Exit of Loops
example:
Sub test_exit()
For x = 1 To 100
If x = 50 Then
Exit For
End If
Next x
MsgBox x
End Sub
Functions
Splitting Strings
x=Mid("12Richard",3)
x=Left("12Richard",2)
x=Right("12Richard",2)
Searching Strings
InStr([start, ]string1, string2[, compare])
Example
Instr("Richard Shepherd","shepherd")
x = Shell("calc.exe")
For n = 1 To 10
Next n
AppActivate "calculator"
End Sub
Errors and the Error
Function
Sub Test_Error()
On Error GoTo err_handler
temp = Dir("a:\*.*")
Exit Sub
err_handler:
If Err.Number = 71 Then
MsgBox "The A drive is not
ready"
Else
MsgBox "An error occurred"
End If
End Sub
The Resume Statement
Sub Test_Error()
temp = Dir("a:\*.*")
End Sub
Dialogs
User Form
Properties
Displaying Your Form in Code
Sub MenuCommand()
CommandBars("Worksheet Menu Bar").Controls _
("Tools").Controls.Add _
(Type:=msoControlButton).Caption = "MyMenu"
CommandBars("Worksheet Menu Bar").Controls _
("Tools").Controls("MyMenu").OnAction = "Test_Menu“
End Sub
Enable And Visible Menu
ActivePrinter Application.ActivePrinter
ActiveSheet Application.ActiveSheet.Cells (10,10).Select
ActiveWindow Application.ActiveWindow.Caption
ActiveWorkbook Application.ActiveWorkbook.Name
AddIns
Sub test()
Dim MyAddin As AddIn
For Each MyAddin In AddIns
MsgBox MyAddin.FullName
Next
End Sub
Caption
Application.Caption = "MyApplication"
Quit
Application.Quit
Sheets
Application.Sheets("sheet1").Print
Undo
Application.Undo
Version
Application.Version
OperatingSystem
Application.OperatingSystem
Workbook Object
SAVE
Workbooks("book1").Save
SAVE AS …
Workbooks("book3").SaveAs "C:\Myfile.xls"
CLOSE
Workbooks(“book3”).Close
Window Objects
Caption
ActiveWindow.Caption = "MyWindow"
Display Properties
DisplayFormulas
DisplayGridlines
DisplayHeadings
DisplayHorizontalScrollBar
DisplayOutline
DisplayRightToLeft Zoom
ActiveWindow.Zoom = 80
DisplayVerticalScrollBar
DisplayworkBookTabs
DisplayZeros
Example
ActiveWindow.DisplayWorkbookTabs = False
Worksheet Object
PrintOut and PrintPreview
Worksheets("sheet2").PrintOut
Worksheets("sheet2").PrintPreview
Protect
Worksheets("sheet2").Protect ("apple")
Un Protect
Worksheets("Sheet2"),Unprotect ("apple")
Visible
Worksheets("sheet2").Visible = False
Range Object
AddComment
Worksheets("sheet1").Range("a1").AddComment ("MyComment")
Clear
Worksheets("sheet2").Range("a3:d12").Clear
ClearContents
Worksheets("sheet2").Range("a3:d12").ClearContents
ClearFormats
Worksheets("sheet2").Range("a3.d12").ClearFormats