0% found this document useful (0 votes)
735 views50 pages

Excel VBA Macro Programming

This document provides an overview of Excel VBA macros and programming. It discusses declaring variables, data types, arrays, constants, modules, functions, subroutines, conditional statements, loops, functions, dialogs, the Excel object model including the Application, Workbook, Worksheet, Window, and Range objects. Key methods and properties are described for tasks like saving, closing, printing, protecting sheets, and more.

Uploaded by

natee8632
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
735 views50 pages

Excel VBA Macro Programming

This document provides an overview of Excel VBA macros and programming. It discusses declaring variables, data types, arrays, constants, modules, functions, subroutines, conditional statements, loops, functions, dialogs, the Excel object model including the Application, Workbook, Worksheet, Window, and Range objects. Key methods and properties are described for tasks like saving, closing, printing, protecting sheets, and more.

Uploaded by

natee8632
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
  • Your First Excel VBA Macro: Introduces writing and executing a simple macro with 'Hello World' example.
  • Variables, Constants, and Data Types: Details how to declare and use variables, constants, and data types in VBA programming.
  • Data Handling: Provides an overview of different data types and how arrays are managed.
  • Modules, Functions, and Subroutines: Covers the concepts of modules, functions, and subroutines, highlighting differences and applications.
  • Programming Basics: Introduces basic programming logic in VBA, including decisions and looping with examples.
  • Functions: Introduces functions available in VBA, explaining commonly used functions with examples.
  • User Interface Commands: Discusses commands affecting the VBA interface such as SendKeys, Dialogs, and PopUp menus.
  • The Excel Object Model: Explains different Excel objects and their properties, crucial for manipulating Excel from VBA.

Excel VBA Macro

Programming
Your First Excel VBA Macro

Private Sub Workbook_NewSheet(ByVal Sh As Object)


MsgBox "Hello World“
End Sub
Variables, Arrays, Constants, and Data
Types
declare a variable using the Dim statement
Dim variablename [As type]
Example
Dim MyInteger as Integer

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

Dim temp (1 To 15) as String

Multidimensional Arrays
Dim temp(10,4) as String
Dim temp(10,4,3) as String
Dynamic Arrays
Dim temp() LBound(temp)

ReDim temp(100) UBound(temp)


Constants

Constants are, in effect, variables that do not


change.

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

use the ByVal or ByRef keyword to define


how parameters are passed to procedure:
example,
x = 100
z = Adjust(x)
Function Adjust(ByRef Target as Integer)

x = 100
z = Adjust(x)
Function Adjust(ByVal Target as Integer)
Programming Basics
Decisions

If..Then..Else

Sub test_if()
If [Link] = 5 Then
MsgBox "Cell is 5"
Else
MsgBox "Cell is not 5"
End If
End Sub
Conditional operators
Multiple Conditional Statements

If x = 1 And y > 5 Then


MsgBox "x=1 and y>5"
Endif

If x = 1 Or y > 5 Then
MsgBox "x=1 or y>5"
End If
Select Case Statements

Select Case Grade


Case 1
Msgbox "Grade 1"
Case 2, 3
Msgbox "Grade 2 or 3"
Case 4 To 6
Msgbox "Grade 4, 5 or 6"
Case Is > 8
MsgBox "Grade is above 8"
Case Else
Msgbox "Grade not in conditional
statements"
End Select
Looping
For..Next Loops
For n= 10 to 1 Step -1
MsgBox n
Next n
For Each Loops
For Each allows you to step through each item within the collection
or array.
Sub ShowName()
Dim oWSheet As Worksheet
For Each oWSheet In Worksheets
MsgBox [Link]
Next oWSheet
End Sub
While..Wend Loops
This continues to loop while a specified
condition is true.
example
Sub test_do()
x =0
While x < 50
x =x +1
Wend
MsgBox x
End Sub
Do Until Loops
keeps looping until a specified condition is met.
example

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)

Dim iValue as Integer


IValue = Val("12")

x=Left("12Richard",2)
x=Right("12Richard",2)
Searching Strings
InStr([start, ]string1, string2[, compare])

Example
Instr("Richard Shepherd","shepherd")

InStr(1, "Richard Shepherd", "shepherd", vbTextCompare)


Conversion Functions
Cstr
Cstr converts a value to a string.
CInt
CInt converts a value or a string to an integer
(2 bytes).
CLng
CLng converts a value or a string to a long
integer (4 bytes).
Conversion Functions
CDbl
CDbl converts a value or a string to a double
precision floating point number (8 bytes)
Val
Val converts a string to a value.
Format Function
Format(1234567.89, "#,###.#")
Date and Time Functions
Now
returns the current date and time
Date
returns the current date in short format
Date can also be used to set the current
system date: Date = "03/31/03"
Time
returns the current system time
Date and Time Functions
DateAdd
allows the addition and subtraction of a
specified time interval to a date.
MsgBox DateAdd ("m",1,"1-Jan-03")
Date and Time Functions
DateDiff
returns the number of time intervals between
two specified dates
DateDiff("m", "1-jan-03", "15-mar-03")
Date and Time Functions
DatePart function returns a specified part of a
given date
MsgBox DatePart("q", "1-mar-03")
SendKeys Command
SendKeys sends one or more keystrokes to
the active window as if they had been
entered at the keyboard:
SendKeys keytext [,wait]
Sub test_sendkeys()

x = Shell("[Link]")

For n = 1 To 10

SendKeys n & "{+}", True

Next n

MsgBox "Press OK to close calculator"

AppActivate "calculator"

SendKeys "%{F4}", True

End Sub
Errors and the Error
Function
Sub Test_Error()
On Error GoTo err_handler
temp = Dir("a:\*.*")
Exit Sub
err_handler:
If [Link] = 71 Then
MsgBox "The A drive is not
ready"
Else
MsgBox "An error occurred"

End If
End Sub
The Resume Statement

Sub Test_Error()

On Error Resume Next

temp = Dir("a:\*.*")

End Sub
Dialogs
User Form
Properties
Displaying Your Form in Code

Private Sub Workbook_NewSheet(ByVal Sh As Object)


[Link]
End Sub
Command Bars and Buttons
Sub Test_Menu()
MsgBox "You pressed my menu item"
End Sub

Sub MenuCommand()
CommandBars("Worksheet Menu Bar").Controls _
("Tools").[Link] _
(Type:=msoControlButton).Caption = "MyMenu"
CommandBars("Worksheet Menu Bar").Controls _
("Tools").Controls("MyMenu").OnAction = "Test_Menu“
End Sub
Enable And Visible Menu

CommandBars("Worksheet Menu Bar"). _


Controls("Tools").Controls("MyMenu").Enabled =
False

CommandBars("Worksheet Menu Bar"). _


Controls("Tools").Controls("MyMenu").Visible =
False
PopUp Menu
Sub Test_Popup()
Dim newsubitem As Object
CommandBars("Worksheet menu bar").Controls("Tools"). _
[Link](Type:=msoControlPopup).Caption = "MyPopup"
Set newsubitem = CommandBars("Worksheet Menu Bar"). _
Controls("Tools").Controls("MyPopup")
With newsubitem
.[Link](Type:=msoControlButton).Caption = "Option1"
.Controls("Option1").OnAction = "Test_Menu"
.[Link](Type:=msoControlButton).Caption = "Option2"
.Controls("Option2").OnAction = "Test_Menu"
End With
End Sub
The Excel Object Model
Application Object
is at the highest point in the hierarchy of the object
model and represents the whole Excel application.
Main Properties, Methods, and Collections
ActiveCell [Link]

ActivePrinter [Link]
ActiveSheet [Link] (10,10).Select

ActiveWindow [Link]

ActiveWorkbook [Link]
AddIns
Sub test()
Dim MyAddin As AddIn
For Each MyAddin In AddIns
MsgBox [Link]
Next
End Sub
Caption
[Link] = "MyApplication"
Quit
[Link]
Sheets
[Link]("sheet1").Print

Undo
[Link]
Version
[Link]
OperatingSystem
[Link]
Workbook Object
SAVE
Workbooks("book1").Save
SAVE AS …
Workbooks("book3").SaveAs "C:\[Link]"

CLOSE
Workbooks(“book3”).Close
Window Objects
Caption
[Link] = "MyWindow"
Display Properties
DisplayFormulas
DisplayGridlines
DisplayHeadings
DisplayHorizontalScrollBar
DisplayOutline
DisplayRightToLeft Zoom
[Link] = 80
DisplayVerticalScrollBar
DisplayworkBookTabs
DisplayZeros
Example
[Link] = 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

Excel VBA Macro 
Programming
Your First Excel VBA Macro 
Private Sub Workbook_NewSheet(ByVal Sh As Object)
MsgBox "Hello World“
End Sub
Variables, Arrays, Constants, and Data 
Types 
declare a variable using the Dim statement 
Dim variablename [As type]
Example
Scope and Lifetime of  Variables
Local Variables 
A local variable uses Dim, Static, or ReDim 
(arrays only) to declare the v
Global Variables 
Global variables are declared in the 
declarations part of a module with the Global
statement 
Example
Glob
Data Types
Arrays
Dim employee1 as String, employee2 as String,.......
Dim employee(25) as String  
Dim temp (1 To 15) as String 
Multid
Constants
Constants are, in effect, variables that do not 
change. 
Example
Const Path_Name = "C:\temp\"
Modules, Functions, and Subroutines 
Modules are where you write your code. 
Functions and subroutines are the two 
different
Public and Private Functions and 
Subroutines 
keyword Public or Private 
Private Sub PrivateSub()
…
End Sub 
Argument Data T

You might also like