Anda di halaman 1dari 47

TUTORIAL - EXCEL MACROS AND VISUAL BASIC

TUTORIAL - EXCEL MACROS AND VISUAL BASIC


If you are using Excel 2010 then load the Developer tab on the Ribbon.
http://office.microsoft.com/en-us/excel-help/save-time-by-creating-and-running-macros-in-excel-2010-RZ102337714.aspx?CTT=1

TUTORIAL - EXCEL MACROS AND VISUAL BASIC

TUTORIAL - EXCEL MACROS AND VISUAL BASIC

Click File\Options\Trust Center\Trust Center Settings\Macro Settings


Set: Enable all macros = Yes

TUTORIAL - EXCEL MACROS AND VISUAL BASIC

Start the Tutorial


Reference: http://www.excel-vba.com/excel-macros-beginners.htm
http://office.microsoft.com/en-us/excel-help/save-time-by-creating-and-running-macros-in-excel-2010-RZ102337714.aspx?CTT=1
http://www.vb6.us/tutorials

Open up EXCEL with a new workbook.

Click on the Visual Basic icon

on the Developer tab, or press keys Alt F11 to

start the VB editor. Press Alt F11 again when you wish to switch back to EXCEL.

TUTORIAL - EXCEL MACROS AND VISUAL BASIC


Learn how to manipulate the Code window.

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

TUTORIAL - EXCEL MACROS AND VISUAL BASIC

Add a sheet in the EXCEL window.

TUTORIAL - EXCEL MACROS AND VISUAL BASIC

Example 1 - Change the name of sheet1 to Introduction

TUTORIAL - EXCEL MACROS AND VISUAL BASIC

Example 2 - Examine the options for the Visible property

Example 3 - Write a macro to write numbers to sheet1


First, change the name of Sheet1 back to Sheet1
Type the following code into the Code window. Do not cut and paste. Type all the
code in lower case.
Sub proFirst()
' This is how you write comments
Rem This is an alternative
Range("A1").Value = 34
Range("A2").Value = 66
Range("A3").Formula = "=A1+A2"
Range("A1").Select
End Sub

Click some where with the code, then click the Run button.

TUTORIAL - EXCEL MACROS AND VISUAL BASIC

Clear cells A1:A3 and in EXCEL click View\Macro\Macros, or Developer\Macros

Examine the debug options.


Clear cells A1:A3 in EXCEL.
Arrange the VBE and EXCEL windows side by side.
Click within the first line of code in the Code window.
Press the F8 key on your computer keyboard.

TUTORIAL - EXCEL MACROS AND VISUAL BASIC

Press the F8 key several times, and watch the code execution in the EXCEL window.

Click on View\Immediate Window


Enter and run the following code, and watch the messages in the Immediate Window.
Sub proFirst()
' The next line prints to the Immediate Window
Debug.Print "start now"
Range("A1").Value = 34
Debug.Print "finished line 1"
Range("A2").Value = 66
Range("A3").Formula = "=A1+A2"
Range("A1").Select
Debug.Print "got to the finish"
End Sub

Try some more examples


Click at the end of the line End Sub and press Enter.
Type in the following examples one by one and test them.
' The sub of name Auto_Open will run automatically
' when the workbook is opened.
Sub Auto_Open()
Debug.Print "HELLO"
End Sub

10

TUTORIAL - EXCEL MACROS AND VISUAL BASIC

Sub TwoLines()
MsgBox "Line 1" &
End Sub

vbCrLf & "Line 2"

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

Select a block of cells on Sheet1, then run the example.


Sub Count()
VBA.Constants.vbNewLine
CountRows = Selection.Rows.Count
CountCols = Selection.Columns.Count
MsgBox "Rows=" & CountRows & vbNewLine & "Cols=" & CountCols
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

Save this group of macros


Open up notepad. Choose a short name your_choice for the module.
Name the module your_choice.bas.
Type in as line 1: Attribute VB_Name = "your_choice"

<= with the quotation " marks

line 2: Option Explicit


Next, select and copy the contents of the code window below these lines.
Save the text file with a .bas extension to one of your directories.
Close the VB editor and this EXCEL file. Exit EXCEL.

11

TUTORIAL - EXCEL MACROS AND VISUAL BASIC


Open EXCEL again with a new workbook.
Press Alt F11 to open the VB editor.
Right click on a blank area of the VBA Project window.
Click on Import File in the popup menu.

The Import File window opens.


Navigate to where you saved your bas file.

Double click on the bas file, or select it and click open.


The file imports into the VB editor as a module named your_choice.
12

TUTORIAL - EXCEL MACROS AND VISUAL BASIC

The code loads into the code window.

Switch back to EXCEL. Click on any worksheet and click View\Macro\Macros.


Browse the Macros window and observe that the set of macros are available to all
worksheets in the workbook.

13

TUTORIAL - EXCEL MACROS AND VISUAL BASIC

14

TUTORIAL - EXCEL MACROS AND VISUAL BASIC

Notes on the VB Language


Comments syntax
' This is a comment on a new line
' This (space then apostophe) is a comment at the end of a line
Rem This is a comment on a new line
:Rem This (space then colon) is a comment at the end of a line
Line continuation syntax is a space followed by an underscore.
..... _
..... _
For statement syntax
For <start_value of i> To <end_value of i>
......
Next i
To jump out of a For statement use the statement Exit For.
If statement syntax
If <conditional_expression> Then
......
End If
Else ' Comment: One or more Else ... End If blocks are optional
......
End If
If

(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

Can hold Dates, Floating Point


Numbers or Strings of
Characters,

Declaring Variables and Constants


Variable:
Dim Variable_Name As Data_Type
Constants:
Constant_Name = Value
Variables do not have to be declared. If they are not declared, they are given the
default Variant data type.
Scope means where a variable name is recognized. If a variable declaration is
outside a subroutine or function, then the variable is recognized by subroutines or
functions in the same module and underneath the declaration.
If a variable is declared at the top of a function or subroutine, then it is limited to
that function or subroutine.
A variable can be declared inside an If or a For block, and is local or limited to
that block of code.
Instead of Dim, variables can be declared as Public or Private.
Public means available to all modules. Private means available to the current
module only.
Static variables
Specifies that one or more declared local variables are to continue to exist and
retain their latest values after termination of the procedure in which they are declared.
Example of a Static variable
Function updateSales(ByVal thisSale As Decimal) As Decimal
Static totalSales As Decimal = 0

TUTORIAL - EXCEL MACROS AND VISUAL BASIC

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

TUTORIAL - EXCEL MACROS AND VISUAL BASIC

It is optional where arguments are passed to the subroutine or function.


Sub AddToCells(i As Integer)
.....
End Sub
A subroutine or function can be declared with optional arguments
' The subroutine is declared with i as an optional argument
Sub AddToCells(Optional i As Integer)
....
If IsMissing(i) Then
' If i was not passed, then do this code block
....
Else
' If i was passed, then do this code block
....
End If
End Sub
Optional arguments can be given a default value which is used if the arguement is
missing. e.g.
Sub AddToCells(Optional i As Integer = 4)
Arguments can be passed using the ByVal keyword or the ByRef keyword.
ByVal means a copy of the argument is passed to the function. The function changes
the copy inside itself, and not the value inside the upper function which made the
call.
ByRef means that the memory address of the variable is passed from the calling
function to the called function. This allows the called function to change the contents
of the memory address. This is almost the same as passing a pointer in C/C++.
Sub AddToCells(ByVal i As Integer)
....
End Sub
Sub AddToCells(ByRef i As Integer)
....
End Sub
You can force passing by value by passing the argument enclosed in parentheses.
e.g. AddToCells( (5) )

18

TUTORIAL - EXCEL MACROS AND VISUAL BASIC

Example of a subroutine calling a function


Sub add_these()
x = SumMinus(8, 9, 4)
MsgBox ("x=" & x)
End Sub
Function SumMinus(

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

TUTORIAL - EXCEL MACROS AND VISUAL BASIC

Call a User Defined function from EXCEL


http://www.exceltip.com/st/Writing_Your_First_VBA_Function_in_Excel/631.html

20

TUTORIAL - EXCEL MACROS AND VISUAL BASIC

Function Area(Length As Double, Width As Double)


Area = Length * Width
End Function
Type the formula =Area(A1,B1) into cell C1.

Select Case Statement


Syntax - Select Case
Select Case expression
Case value1
Block of one or more VB statements
Case value2
Block of one or more VB Statements
Case value3
....
....
Case Else
Block of one or more VB Statements
End Select

21

TUTORIAL - EXCEL MACROS AND VISUAL BASIC

Example of a Select Case statement


' Put a string such as A or A- in cell B2
' then run this example
Sub Compute_Click()
Dim grade As String
Dim caption As String
grade = Cells(2, 2).Value
Select Case grade
Case "A"
caption = "High Distinction"
Case "A-"
caption = "Distinction"
Case "B"
caption = "Credit"
Case "C"
caption = "Pass"
Case Else
caption = "Fail"
End Select
MsgBox ("Result=" & caption)
End Sub
Do Loops
Syntax of a Do loop
' Alternative 1
Do While <condition> ' <condition> means a logical expression
....
' The next line jumps out of the Do loop if the
' logical expression is satisfied.
If <logical_expression> Then Exit Do End If
....
Loop
' Alternative 2
Do
....
Loop While <condition>
' Alternative 3
Do Until <condition>
....
Loop
' Alternative 4
Do
....
Loop Until <condition>

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?

TUTORIAL - EXCEL MACROS AND VISUAL BASIC

A class is similar to a block of memory containing variables, functions, and other


things.
You can call up this block of memory and use dot notation to call one of the things
inside the block.
In VBA you create the block of memory using the Set statement, and record its
start position with a pointer.
Example - Classes

Load the module CLASS_EXAMPLE_1 and the class file clsEX3


Make sure the Immediate W indow is showing.
Click somewhere inside the sub and then click the Run button.
The results will show in the Immediate window.
The module CLASS_EXAMPLE_1
Option Explicit
' instance_of_class_ex3 is going to point at an
' instance of class clsEX3
Dim instance_of_class_ex3 As clsEX3
' =================================================
Sub call_class_example_01()
' The notation (+) means enter the procedure
Debug.Print ("call_class_example_01(+)")
' Declare variables
Dim temp_str As String
' https://msdn.microsoft.com/en-us/library/office/gg251642.aspx
' point instance_of_class_ex3 at a new instance of clsEX3
Set instance_of_class_ex3 = New clsEX3
' call the Let Name property in clsEX3
' https://msdn.microsoft.com/en-us/library/office/gg264823.aspx
instance_of_class_ex3.let_push_name_into_clsex3 = "CLASS_EXAMPLE bob"
temp_str = instance_of_class_ex3.get_pull_name_from_clsex3
Debug.Print "temp_str=" & temp_str
instance_of_class_ex3.call_sub_02
' The notation (-) means leave the procedure and return
' to the calling function
Debug.Print ("call_class_example_01(-)")
End Sub

24

TUTORIAL - EXCEL MACROS AND VISUAL BASIC

Class file clsEX3


Option Explicit
' -----------------------------------Private pName As String
' -----------------------------------' get_pull_name_from_clsex3() is called from inside
' another module/class to send the value of pName
' from here to the calling module/class
Public Property Get get_pull_name_from_clsex3() As String
Debug.Print "clsEX3 Get get_pull_name_from_clsex3"
get_pull_name_from_clsex3 = pName
End Property
' ------------------------------------

' let_push_name_into_clsex3() is called from inside another


' module/class to send the value of pName from the calling
' module/class to here
Public Property Let let_push_name_into_clsex3(value As String)
Debug.Print "clsEX3 Let let_push_name_into_clsex3"
pName = value
End Property
' -----------------------------------Sub call_sub_02()
Debug.Print "THIS IS A TEST"
End Sub
' ------------------------------------

25

TUTORIAL - EXCEL MACROS AND VISUAL BASIC

26

TUTORIAL - EXCEL MACROS AND VISUAL BASIC

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

TUTORIAL - EXCEL MACROS AND VISUAL BASIC

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.

How to use Smart Indenter:

28

TUTORIAL - EXCEL MACROS AND VISUAL BASIC

Right click in the code window, then click Smart Indent\Indent Module

29

TUTORIAL - EXCEL MACROS AND VISUAL BASIC

Optional - Download and install the VBA editor Add-In CodeVBA:


http://codevba.com/
http://codevba.com/zips/codevba.zip

Extract the exe file and install the Add-In


The most useful feature is Code Explorer. It gives you a list of every function or
procedure in a module or class file, and allows you to go directly to the code location.

30

TUTORIAL - EXCEL MACROS AND VISUAL BASIC

Optional - Download and install the VBA editor Add-In MZ-Tools:


http://www.mztools.com/v3/download.aspx

31

TUTORIAL - EXCEL MACROS AND VISUAL BASIC


VBA Reference

VBA Reference

Data Types

Data Types

Objects

Objects

Ambiguous selection

Keyword Summaries

Boolean Data Type

LongLong Data Type

Collection Object

Folder Object

Character Sets

Keywords (VBA)

Byte Data Type

LongPtr Data Type

Debug Object

Folders Collection

Constants (VBA)

Methods (VBA)

Currency Data Type

Object Data Type

Dictionary Object

TextStream Object

Data Types

Object Browser (VBA)

Data Type Summary

Single Data Type

Drive Object

UserForm Object

Directives

Objects (VBA)

Date Data Type

String Data Type

Drives Collection

Error Messages

Operators

Decimal Data Type

User-Defined Data Type

Err Object

Events (VBA)

Properties (VBA)

Double Data Type

Variant Data Type

File Object

Functions (VBA)

Statements

Integer Data Type

Files Collection

Keyword Not Found

Strings

Long Data Type

FileSystemObject Object

32

TUTORIAL - EXCEL MACROS AND VISUAL BASIC


STATEMENTS

STATEMENTS

STATEMENTS

STATEMENTS

AppActivate Statement

FileCopy Statement

On Error Statement

Resume Statement

Beep Statement

For Each...Next Statement

On...GoSub, On...GoTo Statements

RmDir Statement

Call Statement

For...Next Statement

Open Statement

RSet Statement

ChDir Statement

Function Statement

Option Base Statement

SaveSetting Statement

ChDrive Statement

Get Statement

Option Compare Statement

Seek Statement

Close Statement

GoSub...Return Statement

Option Explicit Statement

Select Case Statement

Const Statement

GoTo Statement

Option Private 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

Property Get Statement

Static Statement

DeleteSetting Statement

Kill Statement

Property Let Statement

Stop Statement

Dim Statement

Let Statement

Property Set Statement

Sub Statement

Do...Loop Statement

Line Input # Statement

Public Statement

Time Statement

End Statement

Load Statement

Put Statement

Type Statement

Enum Statement

Lock, Unlock Statements

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

TUTORIAL - EXCEL MACROS AND VISUAL BASIC


METHOD

METHOD

METHOD

Add Method (Dictionary)

GetAbsolutePathName Method

OpenTextFile Method

Add Method (Visual Basic for Applications)

GetBaseName Method

Print Method

AddFolders Method

GetDrive Method

PrintForm Method

Assert Method

GetDriveName Method

Raise Method

BuildPath Method

GetExtensionName Method

Read Method

Clear Method (Visual Basic for Applications)

GetFile Method
GetFileName Method (Visual Basic for
Applications)

ReadAll Method

Close Method (FileSystemObject object)

ReadLine Method

Copy Method (Visual Basic for Applications)

GetFolder Method

Remove Method (FileSystemObject


object)

CopyFile Method

GetParentFolderName Method

Remove Method (Visual Basic for


Applications)

CopyFolder Method

GetSpecialFolder Method

RemoveAll Method

CreateFolder Method

GetTempName Method

Show Method

CreateTextFile Method

Hide Method

Skip Method

Delete Method (Visual Basic for Applications)

Item Method (Visual Basic for Applications)

SkipLine Method

DeleteFile Method

Items Method

WhatsThisMode Method

DeleteFolder Method

Keys Method

Write Method

DriveExists Method

Move Method (FileSystemObject object)

WriteBlankLines Method

Exists Method

MoveFile Method

WriteLine Method

FileExists Method

MoveFolder Method

FolderExists Method

OpenAsTextStream Method

34

TUTORIAL - EXCEL MACROS AND VISUAL BASIC

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

IsNumeric Function MsgBox 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

Partition Function Split Function

Val Function

FileAttr Function

Input Function

Len Function

Pmt Function

Sqr Function

VarType Function

FileDateTime Function InputBox 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

Format Function (VBA) Int, Fix Functions

Log Function
LTrim, RTrim, and
Trim Functions

Rate Function

String Function

IPmt Function

MacID Function

Replace Function

StrReverse
Function

IRR Function

MacScript Function RGB 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

DateValue Function FreeFile Function

35

Type Conversion
Functions
TypeName Function
UBound Function
UCase Function

WeekdayName
Function
Year Function

TUTORIAL - EXCEL MACROS AND VISUAL BASIC


Operators

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

Print

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

TUTORIAL - EXCEL MACROS AND VISUAL BASIC


GLOSSARY
access key

by value

Date data type

file number

locale

Object data type

Property procedure

Sub procedure

ActiveX control
ActiveX object

Byte data type


character code

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

ANSI Character Set

class module

DBCS

Function procedure

MDI child

object type

registry

time expression

application
argument

code module
code pane

Decimal data type


declaration

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

ASCII Character Set

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

Single data type

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

numeric data type

procedure call

statement

watch expression
z-order

Automation object
base class
bitmap
bitwise comparison

comparison
operator
compile time
compiler directive
conditional
compiler constant

Boolean data type

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

event source object

line number
line-continuation
character

object

Project window

String data type

breakpoint

Currency data type

executable file

linked window

Object box

Properties window

string expression

by reference

data type

expression

linked window
frame

Object Browser

property

string literal

37

TUTORIAL - EXCEL MACROS AND VISUAL BASIC


access key
ActiveX control
ActiveX object
add-in
ANSI Character Set
application
argument
array
ASCII Character Set
automatic formatting

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

dynamic-link library (DLL) module variable

Single data type

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

Variant data type

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

TUTORIAL - EXCEL MACROS AND VISUAL BASIC

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

TUTORIAL - EXCEL MACROS AND VISUAL BASIC


code module 37
code pane 37
Code window 5
CodeVBA 30
collection 37
Collection Object 32, 36
colon 15
Color scheme 1
Columns.Count 11
Command Function 35
command line 37
comment 15, 37
comment block 27
comments 8
Comments syntax 15
Compare Statement 33
comparison operator 37
Comparison Operators 36
compile time 37
Compiler Directive 36
compiler directive 37
Concatenation Operators 36
conditional compiler constant 37
conditional_expression 15
Const Statement 33
constant 37
Constants (VBA) 32
Constants, Declare 16
Constants.vbNewLine 11
container 37
continuation syntax 15
control 37
control array 37
Control Flow 36
Conversion 36
Conversion Functions 35
Copy Method (VBA 34
CopyFile Method 34
CopyFolder Method 34
Cos Function 35
Count 11
CreateFolder Method 34
CreateObject Function 35
CreateTextFile Method 34
CurDir Function 35
Currency 16
Currency Data Type 32
Currency data type 37
Customize 27
Customize Ribbon 1

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

TUTORIAL - EXCEL MACROS AND VISUAL BASIC


Directories and Files 36
DLL 37
Do Loops 22
Do Until 11, 22
Do While 22
Do...Loop Statement 33
docked window 37
document 37
DoEvents Function 35
dot notation 24
Double 16
Double Data Type 32
Double data type 37
drag window 5
Drive Object 32
DriveExists Method 34
Drives Collection 32
Dynamic Array 17
dynamic data exchange (DDE) 37
dynamic-link library (DLL) 37
E
eadLine Method 34
Editor Format tab 27
Editor tab 27
Else 15, 36
Empty 36, 37
Enable all macros 2
End If 15
End Statement 33
Enum Statement 33
Environ Function 35
EOF Function 35
Equal to 15
Eqv Operator 36
Erase Statement 33
Err Object 32
Error 36
Error Function 35
Error Messages 32
error number 37
Error Statement 33
Errors 36
event source object 37
Event Statement 33
Events (VBA) 32
Excel 2010 1
exe file 30
executable file 37
exist 16

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

TUTORIAL - EXCEL MACROS AND VISUAL BASIC


FV Function 35
G
general procedure 37
Get 25, 36
Get Statement 33
get_pull_name_from_clsex3 25
GetAbsolutePathName Method 34
GetAllSettings Function 35
GetAttr Function 35
GetBaseName Method 34
GetDrive Method 34
GetDriveName Method 34
GetExtensionName Method 34
GetFile Method 34
GetFileName Method (VBA) 34
GetFolder Method 34
GetObject Function 35
GetParentFolderName Method 34
GetSetting Function 35
GetSpecialFolder Method 34
GetTempName Metho 34
GLOSSARY 37
GoSub 33
GoSub...Return Statement 33
GoTo Statement 33
graphics method 37
Greater than 15
Greater than or equal 15
H
Hex Function 35
Hide Method 34
host application 37
Hour Function 35
I
icon 37
identifier 37
If 16
If statement syntax 15
If...Then...Else Statement 33
IIf Function 35
IMEStatus Function 35
Immediate Window 10
Imp Operator 36
Import File 12
in process 37
Indent 27
indent, remove 27
Input 36

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

TUTORIAL - EXCEL MACROS AND VISUAL BASIC


Less than 15
Less than or equal 15
Let 25, 36
Let Statement 33
let_push_name_into_clsex3 25
letters 15
Like Operator 36
Line continuation syntax 15
Line Input # Statement 33
line label 37
line number 37
line-continuation character 37
linked window 37
linked window frame 37
Load Statement 33
Loc Function 35
local 16
locale 37
Lock 36
Lock, Unlock Statements 33
LOF Function 35
Log Function 35
logic error 37
Logical Operators 15, 36
Long 16
Long Data Type 32
Long data type 37
LongLong Data Type 32
LongPtr Data Type 32
Loop 22
Loop Until 22
Loop While 22
lowercase letters 15
LSet Statement 33
LTrim, RTrim, and Trim Functions 35
M
MacID Function 35
macro 8, 11
Macro Settings 2
macros1.bas 11, 12
MacScript Function 35
manipulate the Code window 5
margin indicator 37
Math 36
Math Functions 35
MDI child 37
MDI form 37
Me 36
member 37

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

TUTORIAL - EXCEL MACROS AND VISUAL BASIC


O
Object 16
object 37
Object box 37
Object Browser 37
Object Browser (VBA) 32
Object Data Type 32
Object data type 37
object expression 37
object library 37
object module 37
object type 37
object variable 37
Objects 32
Objects (VBA) 32
Oct Function 35
Offset 11
Ok and Cancel buttons 23
Ok button 23
On 36
On Error Statement 33
On...GoSub, On...GoTo Statements 33
one dimensional array 17
Open Statement 33
OpenAsTextStream Method 34
OpenTextFile Method 34
Operator Precedence 36
Operator Summary 36
Operators 32, 36
Operators, Logical 15
Option 36
Option Base Statement 33
Option Compare Statement 33
Option Explicit Statement 33
Option Private Statement 33
Optional 36
Optional arguments 18
Options 1
options for the Visible property 8
Or 15
Or Operator 36
Outdent 27
P
ParamArray 36
parameter 37
Partition Function 35
path 37
Personalize 1
pi 37

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

TUTORIAL - EXCEL MACROS AND VISUAL BASIC


Randomize Statement 33
Range 8, 10, 11
Range, Data Type 16
Rate Function 35
Read Method 34
ReadAll Method 34
ReadLine Method 34
rearrange the position 5
ReDim 17
ReDim Preserve 17
ReDim Statement 33
referenced project 37
referencing project 37
Registry 36
registry 37
Rem 8, 15
Rem Statement 33
Remove Method (FileSystemObject object)
34
Remove Method (VBA) 34
RemoveAll Method 34
Replace Function 35
Require Variable Declaration 27
Reset Statement 33
resource file 37
Resume 36
Resume Statement 33
Retry and Cancel Buttons 23
Return Statement 33
RGB Function 35
Ribbon 1
Right Function 35
RmDir Statement 33
Rnd Function 35
Round Function 35
Rows.Count 11
RSet Statement 33
run automatically 10
Run button 8, 24
Run Macro 9
run time 37
run-time error 37
S
SaveSetting Statement 33
Scope 16
scope 37
Second Function 35
seed 37
Seek 36

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

TUTORIAL - EXCEL MACROS AND VISUAL BASIC


String Data Type 32
String data type 37
string expression 37
String Function 35
string literal 37
String Manipulation 36
Strings 32
strings 15
StrReverse Function 35
Sub 10
Sub add_these 19
Sub AddToCells 18
Sub Auto_Open 10
Sub call_sub_02 25
Sub Compute_Click 22
Sub CopyRange 11
Sub Count 11
Sub OK_Click 23
Sub procedure 37
Sub proFirst 8, 10
Sub proTest 11
Sub Statement 33
subroutine 16, 19
Subroutines and Functions 17
Switch Function 35
SYD Function 35
Syntax - Select Case 21
syntax checking 37
syntax error 37
Syntax of a Do loop 22
T
Tab Function 35
tab order 37
Tan Function 35
termination of the procedure 16
TextStream Object 32
Then 36
Time 36
time expression 37
Time Function 35
Time Statement 33
Timer Function 35
TimeSerial Function 35
TimeValue Function 35
Title 23
To 36
Tools\Macro\Macros 13
Tools\Options 27
top Editor tool bar 27

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

TUTORIAL - EXCEL MACROS AND VISUAL BASIC


vbRetryCancel 23
vbYesNo 23
vbYesNoCancel 23
View\Macro\Macros 9
Visible property 8
Visual Basic 2
Visual Basic icon 4
W
watch expression 37
watch the code execution 10
Weekday Function 35
WeekdayName Function 35
What is a class 24
WhatsThisMode Method 34
While...Wend Statement 33
Width # Statement 33
Window, Immediate 10
With Statement 33
WithEvents 36
workbook 4
worksheet 6
Write # Statement 33
Write Method 34
WriteBlankLines Method 34
WriteLine Method 34
X
x_Position 23
Xor Operator 36
Y
y_Position 23
Year Function 35
Yes, No and Cancel 23
Z
z-order 37

47

Anda mungkin juga menyukai