Tutorial - Excel Macros and Visual Basic (4feb2015)
Tutorial - Excel Macros and Visual Basic (4feb2015)
start the VB editor. Press Alt F11 again when you wish to switch back to EXCEL.
The windows you need open are Project, Properties and Code. Practice closing and
opening these windows. Note the short cut keys listed in the View menu.
Learn how to rearrange the position and size of the windows.
Rearrange the position and size of the VBE and EXCEL windows so the two windows
are side by side.
5
Click some where with the code, then click the Run button.
Press the F8 key several times, and watch the code execution in the EXCEL window.
10
Sub TwoLines()
MsgBox "Line 1" &
End Sub
Type the following first and second names into columns A and B, then type the
code, then test the macro.
Sub proTest()
Sheets("Sheet1").Select
Range("C1").Select
Do Until Selection.Offset(0, -2).Value = ""
Selection.Value = Selection.Offset(0, -2).Value & _
" " & Selection.Offset(0, -1)
Selection.Offset(1, 0).Select
Loop
Range("A1").Select
End Sub
Type some text into cells A1:A3, click in another cell, then run the example.
Sub CopyRange()
Range("A1:A3").Copy Destination:=ActiveCell
End Sub
11
13
14
(index
Or (index
Or (index
Or (index
Then ...
=
=
=
=
1
2
3
4
And
And
And
And
sColor1
sColor1
sColor1
sColor1
=
=
=
=
"red") _
"blue") _
"green") _
"brown")_
Logical Operators
Operator Meaning
=
>
<
>=
<=
<>
Operator Meaning
Equal to
More than
Less Than
More than and equal
Less than and equal
Not Equal to
You can compare strings with the above operators. Upper case letters are less than
lowercase letters, and numbers are less than letters.
15
Data Types
Data Type Bytes
Description
Byte
1 binary
Boolean
2 True/False
Integer
2 Integer
Long
Single
Double
4
8
Currency
Date
Object
String
Variant
4
varies
Range
0 to 255
True or False
-32,768 to +32767
-2,147,483,648 to
Long Integer
+2,147,483,647
Single precision decimal -3.4e38 to +3.4e38
Double precision decimal -1.8e308 to +1.8e308
-922,337,203,685,477.5808 to
Decimal
+922,337,203,685,477.5807
1st January 100 to 31st
Date/Time
December
Any Object Reference
varies
totalSales += thisSale
Return totalSales
End Function
Arrays
Reference: http://www.excelfunctions.net/Visual-Basic-Arrays.html
An example of a one dimensional array is:
Dim Team_Members(1 To 20) As String ' an array of 20 strings
....
Team_Members(1) = "John Smith"
....
For i = 1 To 20
Cells(i, 1).Value = Team_Members(i)
Next i
An example of a two dimensional array is
Dim Jan_Sales_Figures(1 To 31, 1 To 5) As Currency
Dim Jan_Sales_Figures(31, 5) As Currency ' shorter alternative
Dynamic Array
A dynamic array is declared as variable size, then redeclared with fixed size later
when it is going to be used:
Dim Team_Members() As String
....
ReDim Team_Members(1 To 20)
....
If Team_Size > 20 Then
ReDim Team_Members(1 To Team_Size) ' Lose previous cell values
End If
....
If Team_Size > 20 Then
' The next line is how to keep previous cell values.
' The Preserve keyword has several limitations.
ReDim Preserve Team_Members(1 To Team_Size)
End If
Procedures, Subroutines and Functions
A procedure can be either a subroutine or a function. A function returns a value, a
subroutine does not return a value.
Functions are declared like this:
Function
....
End Function
17
18
dNum1 As Double, _
dNum2 As Double, _
dNum3 As Double) _
As Double
SumMinus = dNum1 + dNum2 - dNum3
End Function
Subroutines and functions can be declared as Public or Private.
Private Sub OK_Click()
firstnum = Val(usernum1.Text)
secondnum = Val(usernum2.Text)
If ((Total = firstnum + secondnum) And (Val(Sum.Text) <> 0))
Then
correct.Visible = True
wrong.Visible = False
Else
correct.Visible = False
wrong.Visible = True
End If
End Sub
19
20
21
22
MsgBox ( ) Function
Syntax of MsgBox
button_clicked_code = MsgBox(display_string, Style Value, Title)
Style value
0
1
2
3
4
5
Named Constant
vbOkOnly
vbOkCancel
vbAbortRetryIgnore
vbYesNoCancel
vbYesNo
vbRetryCancel
Buttons Displayed
Ok button
Ok and Cancel buttons
Abort, Retry and Ignore
Yes, No and Cancel
Yes and No buttons
Retry and Cancel buttons
Return codes
Value
1
2
3
4
5
6
7
Named Constant
vbOk
vbAbort
vbRetry
vbIgnore
vbYesNoCancel
vbYes
vbNo
Button Clicked
OK
Cancel
Abort
Rety
Ignore
Yes
No
InputBox( ) Function
' Syntax
myMessage = InputBox(Prompt, _
Title, _
default_text, _
x_Position, _
y_Position)
Sub OK_Click()
Dim userMsg As String
userMsg = InputBox("What is your message?", _
"Message Entry Form", _
"Enter your messge here", _
500, _
700 _
)
If (userMsg <> "") Then
MsgBox ("You entered=" & userMsg)
End If
End Sub
What is a class?
24
25
26
Appendix 1
Click Tools\Options. Click the Editor tab and browse the settings. Ensure that the
settings Auto Indent and Require Variable Declaration are both ticked. Click the
Editor Format tab. Browse the text fonts and colours. Click OK and close the dialogue.
Right click on the top Editor tool bar, then click Customize.
These commands allow you to select a block of code and then comment the whole
block, or uncomment, indent, or outdent (remove the indent).
27
Optional - Download and install the VBA editor Add-In Smart Indenter:
http://www.oaltd.co.uk/indenter/default.htm
After you have installed Smart Indenter, view your VBA editor Add-Ins.
28
Right click in the code window, then click Smart Indent\Indent Module
29
30
31
VBA Reference
Data Types
Data Types
Objects
Objects
Ambiguous selection
Keyword Summaries
Collection Object
Folder Object
Character Sets
Keywords (VBA)
Debug Object
Folders Collection
Constants (VBA)
Methods (VBA)
Dictionary Object
TextStream Object
Data Types
Drive Object
UserForm Object
Directives
Objects (VBA)
Drives Collection
Error Messages
Operators
Err Object
Events (VBA)
Properties (VBA)
File Object
Functions (VBA)
Statements
Files Collection
Strings
FileSystemObject Object
32
STATEMENTS
STATEMENTS
STATEMENTS
AppActivate Statement
FileCopy Statement
On Error Statement
Resume Statement
Beep Statement
RmDir Statement
Call Statement
For...Next Statement
Open Statement
RSet Statement
ChDir Statement
Function Statement
SaveSetting Statement
ChDrive Statement
Get Statement
Seek Statement
Close Statement
GoSub...Return Statement
Const Statement
GoTo Statement
SendKeys Statement
Date Statement
If...Then...Else Statement
Print # Statement
Set Statement
Declare Statement
Implements Statement
Private Statement
SetAttr Statement
Deftype Statements
Input # Statement
Static Statement
DeleteSetting Statement
Kill Statement
Stop Statement
Dim Statement
Let Statement
Sub Statement
Do...Loop Statement
Public Statement
Time Statement
End Statement
Load Statement
Put Statement
Type Statement
Enum Statement
RaiseEvent Statement
Unload Statement
Erase Statement
LSet Statement
Randomize Statement
While...Wend Statement
Error Statement
Mid Statement
ReDim Statement
Width # Statement
Event Statement
MkDir Statement
Rem Statement
With Statement
Exit Statement
Name Statement
Reset Statement
Write # Statement
33
METHOD
METHOD
GetAbsolutePathName Method
OpenTextFile Method
GetBaseName Method
Print Method
AddFolders Method
GetDrive Method
PrintForm Method
Assert Method
GetDriveName Method
Raise Method
BuildPath Method
GetExtensionName Method
Read Method
GetFile Method
GetFileName Method (Visual Basic for
Applications)
ReadAll Method
ReadLine Method
GetFolder Method
CopyFile Method
GetParentFolderName Method
CopyFolder Method
GetSpecialFolder Method
RemoveAll Method
CreateFolder Method
GetTempName Method
Show Method
CreateTextFile Method
Hide Method
Skip Method
SkipLine Method
DeleteFile Method
Items Method
WhatsThisMode Method
DeleteFolder Method
Keys Method
Write Method
DriveExists Method
WriteBlankLines Method
Exists Method
MoveFile Method
WriteLine Method
FileExists Method
MoveFolder Method
FolderExists Method
OpenAsTextStream Method
34
FUNCTION
Abs Function
FUNCTION
Day Function
FUNCTION
FV Function
GetAllSettings
Function
FUNCTION
IsError Function
FUNCTION
MIRR Function
FUNCTION
Second Function
FUNCTION
Time Function
Array Function
DDB Function
IsMissing Function
Month Function
Seek Function
Timer Function
Asc Function
Derived Math
Functions
GetAttr Function
IsNull Function
MonthName
Function
Sgn Function
TimeSerial Function
Atn Function
Dir Function
GetObject Function
Shell Function
TimeValue Function
DoEvents Function
GetSetting Function
IsObject Function
Now Function
Sin Function
Environ Function
EOF Function
Error Function
Hex Function
Hour Function
IIf Function
Join Function
LBound Function
LCase Function
NPer Function
NPV Function
Oct Function
SLN Function
Space Function
Spc Function
Exp Function
IMEStatus Function
Left Function
Val Function
FileAttr Function
Input Function
Len Function
Pmt Function
Sqr Function
VarType Function
Loc Function
PPmt Function
Str Function
Weekday Function
CurDir Function
FileLen Function
InStr Function
LOF Function
PV Function
StrComp Function
CVErr Function
Filter Function
InStrRev Function
QBColor Function
StrConv Function
Date Function
Log Function
LTrim, RTrim, and
Trim Functions
Rate Function
String Function
IPmt Function
MacID Function
Replace Function
StrReverse
Function
IRR Function
Switch Function
IsArray Function
Math Functions
Right Function
SYD Function
IsDate Function
Mid Function
Rnd Function
Tab Function
IsEmpty Function
Minute Function
Round Function
Tan Function
CallByName
Function
Choose Function
Chr Function
Command Function
Conversion
Functions
Cos Function
CreateObject
Function
FormatCurrency
Function
FormatDateTime
DateDiff Function
Function
FormatNumber
DatePart Function
Function
FormatPercent
DateSerial Function
Function
DateAdd Function
35
Type Conversion
Functions
TypeName Function
UBound Function
UCase Function
WeekdayName
Function
Year Function
Operators
Keyword
Keyword
Keyword
Keyword
Summary
- Operator
Concatenation Operators
As
Len
Property
& Operator
Eqv Operator
Binary
Let
PtrSafe
* Operator
Imp Operator
ByRef
Lock
Public
/ Operator
Is Operator
ByVal
Me
Resume
Control Flow
\ Operator
Like Operator
Date
Mid
Seek
Conversion
^ Operator
Logical Operators
Else
New
Set
Data Types
+ Operator
Mod Operator
Empty
Next
Static
= Operator
Not Operator
Error
Nothing
Step
AddressOf Operator
Operator Precedence
FALSE
Null
String
Errors
And Operator
Operator Summary
For
On
Then
Financial
Arithmetic Operators
Or Operator
Friend
Option
Time
Input and
Output
Comparison Operators
Xor Operator
Get
Optional
To
Math
Input
ParamArray
TRUE
Miscellaneous
Is
WithEvents
Operators
Keywords by Task
Private
36
Arrays
Collection
Object
Compiler
Directive
Dates and
Times
Directories and
Files
Registry
Keyword
Summary
String
Manipulation
Variables and
Constants
by value
file number
locale
Property procedure
Sub procedure
ActiveX control
ActiveX object
date expression
date literal
focus
form
logic error
Long data type
object expression
object library
Public
referenced project
syntax checking
syntax error
add-in
class
date separators
form module
margin indicator
object module
referencing project
tab order
class module
DBCS
Function procedure
MDI child
object type
registry
time expression
application
argument
code module
code pane
general procedure
graphics method
MDI form
member
object variable
parameter
resource file
run time
array
collection
design time
host application
metafile
path
run-time error
twip
type library
type-declaration
character
command line
designer
icon
method
pi
scope
Unicode
automatic
formatting
comment
development
environment
identifier
module
point
seed
universal date
format
docked window
in process
module level
print zone
user-defined type
document
Double data type
dynamic data
exchange (DDE)
dynamic-link
library (DLL)
insertable object
Integer data type
module variable
named argument
Private
procedure
sort order
stack
variable
Variant data type
intrinsic constants
Null
Procedure box
standard module
variant expression
keyword
procedure call
statement
watch expression
z-order
Automation object
base class
bitmap
bitwise comparison
comparison
operator
compile time
compiler directive
conditional
compiler constant
constant
Boolean expression
container
Empty
line label
numeric expression
procedure level
string comparison
bound control
control
error number
numeric type
project
string constant
break mode
control array
line number
line-continuation
character
object
Project window
breakpoint
executable file
linked window
Object box
Properties window
string expression
by reference
data type
expression
linked window
frame
Object Browser
property
string literal
37
GLOSSARY
date expression
logic error
date literal
Long data type
date separators
margin indicator
DBCS
MDI child
dynamic data exchange
MDI form
(DDE)
Decimal data type
member
declaration
metafile
designer
method
design time
module
development
module level
environment
Property procedure
Public
referenced project
referencing project
registry
resource file
run-time error
run time
scope
seed
base class
bitmap
bitwise comparison
Boolean expression
Boolean data type
bound control
break mode
breakpoint
by reference
Byte data type
by value
character code
class
class module
code module
code pane
docked window
document
Double data type
Empty
error number
event source object
executable file
expression
file number
focus
form
form module
Function procedure
general procedure
graphics method
named argument
Null
numeric data type
numeric expression
numeric type
object
Object box
Object Browser
Object data type
object expression
object library
object module
object type
object variable
Automation object
collection
host application
parameter
command line
comment
comparison operator
compiler directive
compile time
conditional compiler
constant
constant
icon
identifier
in process
insertable object
Integer data type
path
pi
point
print zone
Private
sort order
stack
standard module
statement
string comparison
string constant
String data type
string expression
string literal
Sub procedure
syntax checking
syntax error
tab order
time expression
twip
type-declaration
character
type library
Unicode
universal date format
user-defined type
variable
intrinsic constants
procedure
keyword
line-continuation
character
line label
line number
linked window
linked window frame
locale
Procedure box
variant expression
procedure call
watch expression
procedure level
project
Project window
Properties window
property
z-order
container
control
control array
Currency data type
data type
Date data type
38
Index
automatic formatting 37
Automation object 37
B
Symbols
& Operator 36
* Operator 36
+ Operator 36
- Operator 36
/ Operator 36
= Operator 36
\ Operator 36
^ Operator 36
A
Abort, Retry and Ignore 23
Abs Function 35
access key 37
ActiveX control 37
ActiveX object 37
Add a sheet 6
add a sheet 7
Add Method (Dictionary) 34
Add Method (VBA) 34
add-in 37
Add-Ins 1, 28
AddFolders Method 34
AddressOf Operator 36
Alt F11 2, 4, 12
Ambiguous selection 32
And Operator 36
ANSI Character Set 37
AppActivate Statement 33
Appendix 1 27
Appendix 2 - URLS 32
application 37
argument 37
Arguments 18
Arithmetic Operators 36
array 37
Array, Dynamic 17
Array Function 35
Arrays 17, 36
As 36
Asc Function 35
ASCII Character Set 37
Assert Method 34
Atn Function 35
Auto Indent 27
Auto_Open 10
bas extension 11
base class 37
Beep Statement 33
Binary 36
bitmap 37
bitwise comparison 37
Boolean 16
Boolean Data Type 32
Boolean data type 37
Boolean expression 37
bound control 37
break mode 37
breakpoint 37
BuildPath Method 34
by reference 37
by value 37
ByRef 18, 36
Byte 16
Byte Data Type 32
Byte data type 37
ByVal 18, 36
C
Call a User Defined function 20
Call Statement 33
CallByName Function 35
Case Else 21
Case expression 21
Case value1 21
cell values 17
Change the name of sheet 7
character code 37
Character Sets 32
ChDir Statement 33
ChDrive Statement 33
Choose Function 35
Chr Function 35
class 24, 37
class module 37
CLASS_EXAMPLE_1 24
Clear Method (VBA) 34
Close Method (FileSystemObject object)
34
Close Statement 33
clsEX3 24
Code 5
code execution 10
39
CVErr Function 35
D
data type 37
Data Type Summary 32
Data Types 16, 32, 36
Date 16, 36
Date Data Type 32
Date data type 37
date expression 37
Date Function 35
date literal 37
date separators 37
Date Statement 33
DateAdd Function 35
DateDiff Function 35
DatePart Function 35
Dates and Times 36
DateSerial Function 35
DateValue Function 35
Day Function 35
DBCS 37
DDB Function 35
Debug 10
Debug Object 32
debug options 9
Decimal Data Type 32
Decimal data type 37
declaration 37
Declare Statement 33
Declaring Variables and Constants 16
default value 18
default_text 23
Deftype Statements 33
Delete Method (VBA) 34
DeleteFile Method 34
DeleteFolder Method 34
DeleteSetting Statement 33
Derived Math Functions 35
design time 37
designer 37
Destination 11
Developer 2
Developer tab 1, 4
development environment 37
Dictionary Object 32
Dim 16
Dim Statement 33
Dir Function 35
Directives 32
40
Exists Method 34
Exit For 15
Exit Statement 33
Exp Function 35
Explicit Statement 33
expression 37
F
F8 key 9
FALSE 36
File, Import 12
file number 37
File Object 32
FileAttr Function 35
FileCopy Statement 33
FileDateTime Function 35
FileExists Method 34
FileLen Function 35
Files Collection 32
FileSystemObject Object 32
Filter Function 35
Financial 36
focus 37
Folder Object 32
FolderExists Method 34
Folders Collection 32
font 1
For 16, 36
For Each...Next Statement 33
For, Exit 15
For statement syntax 15
For...Next Statement 33
form 37
form module 37
Format Function (VBA) 35
FormatCurrency Function 35
FormatDateTime Function 35
FormatNumber Function 35
FormatPercent Function 35
Formula 8
FreeFile Function 35
Friend 36
FUNCTION 35
function 16
Function Area 20, 21
Function procedure 37
Function Statement 33
Function SumMinus 19
Functions 17
Functions (VBA) 32
41
Input # Statement 33
Input and Output 36
Input Function 35
InputBox Function 35
InputBox( ) Function 23
insertable object 37
InStr Function 35
InStrRev Function 35
Int, Fix Functions 35
Integer 16
Integer Data Type 32
Integer data type 37
intrinsic constants 37
IPmt Function 35
IRR Function 35
Is 36
Is Operator 36
IsArray Function 35
IsDate Function 35
IsEmpty Function 35
IsError Function 35
IsMissing 18
IsMissing Function 35
IsNull Function 35
IsNumeric Function 35
IsObject Function 35
Item Method (VBA) 34
Items Method 34
J
Join Function 35
K
key strokes 2
Keys Method 34
keys, short cut 5
Keyword 36
keyword 37
Keyword Not Found 32
Keyword Summaries 32
Keyword Summary 36
Keywords (VBA) 32
Keywords by Task 36
Kill Statement 33
L
LBound Function 35
LCase Function 35
Left Function 35
Len 36
Len Function 35
42
memory 24
metafile 37
Method 34
method 37
Methods (VBA) 32
Mid 36
Mid Function 35
Mid Statement 33
Minute Function 35
MIRR Function 35
Miscellaneous 36
MkDir Statement 33
Mod Operator 36
module 16, 20, 37
module level 37
module variable 37
Month Function 35
MonthName Function 35
More than 15
More than and equal 15
Move Method (FileSystemObject object) 34
MoveFile Method 34
MoveFolder Method 34
mplements Statement 33
MsgBox 11, 22
MsgBox ( ) Function 23
MsgBox Function 35
MZ-Tools 31
N
Name Statement 33
named argument 37
New 36
new workbook 4
Next 36
Next Statement 33
Not equal to 15
Not Operator 36
notation (+) 24
notepad 11
Nothing 36
Now Function 35
NPer Function 35
NPV Function 35
Null 36, 37
numbers 15
numeric data type 37
numeric expression 37
numeric type 37
43
Pmt Function 35
pName 25
point 37
popup menu 12
PPmt Function 35
Preserve 17
Print 36
Print # Statement 33
Print Method 34
print zone 37
PrintForm Method 34
Private 16, 19, 36, 37
Private pName As String 25
Private Statement 33
Private Sub OK_Click 19
procedure 37
Procedure box 37
procedure call 37
procedure level 37
Procedures, Subroutines and Functions 17
Project 5
project 37
Project window 37
Prompt 23
Properties 5
Properties (VBA) 32
Properties window 37
Property 36
property 37
Property Get 25
Property Get Statement 33
Property Let 25
Property Let Statement 33
Property procedure 37
Property Set Statement 33
PtrSafe 36
Public 16, 19, 36, 37
Public Property Get 25
Public Property Let 25
Public Statement 33
pull 24
push 24
Put Statement 33
PV Function 35
Q
QBColor Function 35
R
Raise Method 34
RaiseEvent Statement 33
44
Seek Function 35
Seek Statement 33
Select 8
Select Case Statement 21, 33
Select Case statement 22
Selection 11
Selection.Columns.Count 11
Selection.Rows.Count 11
SendKeys Statement 33
Set 36
Set Statement 33
SetAttr Statement 33
Sgn Function 35
sheet, add 7
sheet, move 7
sheet, rename 7
Shell Function 35
short cut keys 5
Show Method 34
Sin Function 35
Single 16
Single Data Type 32
Single data type 37
size of the windows 5
Skip Method 34
SkipLine Method 34
SLN Function 35
Smart Indenter 28
sort order 37
space followed by an underscore 15
Space Function 35
Spc Function 35
Split Function 35
Sqr Function 35
stack 37
standard module 37
statement 37
STATEMENTS 33
Statements 32
Static 36
Static Statement 33
Static variables 16
Step 36
Stop Statement 33
Str Function 35
StrComp Function 35
StrConv Function 35
String 16, 36
string comparison 37
string constant 37
45
TRUE 36
Trust Center 1, 2
twip 37
Type Conversion Functions 35
type library 37
Type Statement 33
type-declaration character 37
TypeName Function 35
U
UBound Function 35
UCase Function 35
uncomment block 27
underneath the declaration 16
underscore 15
Unicode 37
universal date format 37
Unload Statement 33
Upper case 15
User Defined function 20
User-Defined Data Type 32
user-defined type 37
UserForm Object 32
V
Val Function 35
Value 8, 10, 11
variable 37
Variables and Constants 36
Variables, Declare 16
Variant 16
Variant Data Type 32
Variant data type 37
variant expression 37
VarType Function 35
VB Language 15
VBA editor Add-Ins 28
VBA project object model 2
VBA Project window 12
VBA Reference 32
VBA.Constants.vbNewLine 11
vbAbort 23
vbAbortRetryIgnore 23
vbCrLf 11
vbIgnore 23
vbNewLine 11
vbNo 23
vbOk 23
vbOkCancel 23
vbOkOnly 23
vbRetry 23
46
47