Sei sulla pagina 1di 20

Excel VBA Macro Manual

Pre lunch Session


I. Introduction to VBA Macros
Developed by Micosoft
A tool that helps develop programs that control excel
Macro comes from the work Makros meaning LARGE.
II. Objective of developing VBA Macro Codes
Inserting a bunch of Text
Automating a task you perform frequently
Automating repetitive operations
Creating a custom command
Creating a custom button
Developing new worksheet functions

III. Introduction to various objects and properties to be used in VBA Language


What do you mean by an Object?
Most programming languages today deal with objects, a concept called object oriented programming.
Although Excel VBA is not a truly object oriented programming language, it does deal with objects. VBA
object is something like a tool or a thing that has certain functions and properties, and can contain data.
For example, an Excel Worksheet is an object, cell in a worksheet is an object, range of cells is an object,
font of a cell is an object, a command button is an object, and a text box is an object and more.
In order to view the VBA objects, you can insert a number of objects or controls into the worksheet, and
click the command button to go into the code window. The upper left pane of the code window contains
the list of objects you have inserted into the worksheet; you can view them in the dropdown dialog
when you click the down arrow. The right pane represents the events associated with the objects.
Object Properties
An Excel VBA object has properties and methods. Properties are like the characteristics or attributes of
an object. For example, Range is an Excel VBA object and one of its properties is value. We connect an
object to its property by a period(a dot or full stop). The following example shows how we connect the
property value to the Range object.
Example
Private Sub CommandButton1_Click()
Range("A1:A6").Value = 10
End Sub

The information provided on these pages remains, unless otherwise stated, the copyright of the respective authors. All layout , design, original graphics, concepts and
other World Wide Web Intellectual Property Rights barring the information mentioned above, remains the property and copyright of OrangeTree Global

Example
Private Sub CommandButton1_Click()
Range("A1:A6")= 10
End Sub
Cells is also an Excel VBA object, but it is also the property of the range object. So an object can also be a
property, it depends on the hierarchy of the objects. Range has higher hierarchy than cells, and interior
has lower hierarchy than Cells, and color has lower hierarchy than Interior, so you can write
Range("A1:A3").Cells(1, 1).Interior.Color = vbYellow .
This statement will fill cells (1,1) with yellow color. Notice that although the Range object specifies a
range from A1 to A3, but the cells property specifies only cells(1,1) to be filled with yellow color, it sort
of overwrite the range specified by the Range object.
Another object is font that belong to the Range object. And font has its properties.For example,
Range(A1:A4).Font.Color=vbYellow , the color property of the object Font will result in all the contents
from cell A1 to cell A4 to be displayed in yellow color.
Sometime it is not necessary to type the properties, Excel VBA IntelliSense will display a drop-down list
of proposed properties after you type a period at the end of the object name. You can then select the
property you want by double clicking the it or by highlighting it then press the Tab key.
IV. The Concept of Variables
Variables are like mail boxes in the post office. The contents of the variables changes every now and
then, just like the mail boxes. In VBA, variables are areas allocated by the computer memory to hold
data. Like the mail boxes, each variable must be given a name. To name a variable in VBA, you have to
follow a set of rules, as follows:

The Concept of Variables

It must be less than 255 characters


No spacing is allowed
It must not begin with a number
Period is not permitted

The information provided on these pages remains, unless otherwise stated, the copyright of the respective authors. All layout, design, original graphics, co ncepts and
other World Wide Web Intellectual Property Rights barring the information mentioned above, remains the property and copy right of OrangeTree Global

Declaring Variables
In VBA, one needs to declare the variables before using them by assigning names and data types. There
are many VBA data types, which can be grossly divided into two types, namely the numeric data types
and non-numeric data types
Numeric Data Types
Numeric data types are types of data that consist of numbers, which can be computed mathematically
with various standard operators such as add, minus, multiply, divide and so on. In VBA, the numeric data
are divided into 7 types

Non-numeric Data Types

You can declare the variables implicitly or explicitly. For example, sum=text1.text means that the
variable sum is declared implicitly and ready to receive the input in Text1 textbox. Other examples of
implicit declaration are volume=8 and label=Welcome. On the other hand, for explicit declaration,
variables are normally declared in the general section of the codes' windows using the Dim statement.
The format is as follows:
Dim variableName as DataType

Dim password As String


Dim yourName As String
Dim firstnum As Integer
Dim secondnum As Integer
The information provided on these pages remains, unless otherwise stated, the copyright of the respective authors. All layout, design, original graphics, co ncepts and
other World Wide Web Intellectual Property Rights barring the information mentioned above, remains the property and copy right of OrangeTree Global

Dim total As Integer


Dim BirthDay As Date
You may also combine them in one line, separating each variable with a comma, as follows:
Dim password As String, yourName As String, firstnum As Integer.
If the data type is not specified, VB will automatically declare the variable as a Variant. For string
declaration, there are two possible formats, one for the variable-length string and another for the fixedlength string. However, for the fixed-length string, you have to use the format as shown below:
Dim VariableName as String * n
where n defines the number of characters the string can hold. For example, Dim yourName as String *
10 mean yourName can hold no more than 10 Characters.

Creating a module
In general, a VBA module can hold three types of code:
Declarations: One or more information statements that you provide to VBA. For example, you can
declare the data type for variables you plan to use, or set some other module-wide options.
Sub procedures: A set of programming instructions that performs some action.
Function procedures: A set of programming instructions that returns a single value (similar in concept to
a worksheet function, such as SUM). A single VBA module can store any number of Sub procedures,
Function procedures, and declarations. How you organize a VBA module is completely up to you. Some
people prefer to keep all their VBA code for an application in a single VBA module; others like to split up
the code into several different modules. Its a personal choice.
Getting VBA code into a module
An empty VBA module is like the fake food you see in the windows of some Chinese restaurants; it looks
good but it doesnt really do much for you.
Before you can do anything meaningful, you must have some VBA code in the VBA module. You can get
VBA code into a VBA module in three ways:
1. Enter the code directly.
2. Use the Excel macro recorder to record your actions and convert them to VBA code
3. Copy the code from one module and paste it into another

V. Understanding Macro security and saving a workbook with Macro contents.


Macro security is a key feature in Excel 2007. The reason is that VBA is a powerful language so
powerful that even a simple macro can do serious damage to your computer. A macro can delete files,
send information to other computers, and even destroy Windows so that your system cant even be
started. The macro security features in Excel 2007 were created to help prevent these types of
problems. To display this dialog box, choose Developer Macro Security. By default, Excel uses the
Disable All Macros with Notification section. If you are certain that the workbook comes from a trusted
source, click Enable Macros, and the macros will be enabled. Perhaps the best way to handle macro
security is to designate one or more folders as trusted locations. All the workbooks in a trusted location
The information provided on these pages remains, unless otherwise stated, the copyright of the respective authors. All layout, design, original graphics, co ncepts and
other World Wide Web Intellectual Property Rights barring the information mentioned above, remains the property and copy right of OrangeTree Global

are opened without a macro warning. You designate trusted folders in the Trusted Locations section of
the Trust Center dialog box.
If you want to find out what the other macro security settings imply, press F1 while the Macro Settings
section of the Trust Center dialog box is in view. The Help screen opens up and the subject Enable or
disable macros in Office documents is shown in the Help window.

VBA Codes Example


'Activating Sheet 1 and Selecting the Cells A1:D10
Sub Range_Property()
Sheet1.Activate
Range("A1:D10").Select
End Sub
'Activating Sheet 1 and Selecting the Cell B1
Sub range_property1()
Sheet1.Activate
Range("B1").Select
End Sub
'Using a Union operator in range selection
Sub range_property2()
Sheet1.Activate
Range("B2:C4, D5:F6").Select
End Sub
'Using an intersection operator in range selection
Sub range_propery3()
Sheet2.Activate
Range("B2:C4 B1:F2").Select
End Sub
The information provided on these pages remains, unless otherwise stated, the copyright of the respective authors. All layout, design, original graphics, co ncepts and
other World Wide Web Intellectual Property Rights barring the information mentioned above, remains the property and copy right of OrangeTree Global

'Selecting one column


Sub column_property()
Sheet1.Activate
Columns("A:A").Select
End Sub
'Selecting two column
Sub column_property1()
Sheet1.Activate
Columns("A:B").Select
End Sub

'Selecting one Row


Sub rows_property()
Sheet1.Activate
Rows("10").Select
End Sub

'Selecting multiple rows


Sub rows_property1()
Sheet1.Activate
Rows("10:15").Select
Selection.Interior.ColorIndex = 20
End Sub

' Activating a cell


Sub cells_property()
The information provided on these pages remains, unless otherwise stated, the copyright of the respective authors. All layout, design, original graphics, co ncepts and
other World Wide Web Intellectual Property Rights barring the information mentioned above, remains the property and copy right of OrangeTree Global

Sheet2.Activate
Cells(3, 6).Select
End Sub
' Adding a worksheet
Sub AddWorksheet()
Worksheets.Add().Name = "MySheet"
End Sub

'Deleting a worksheet
Sub deleteWorksheet()
Worksheets("MySheet").Delete
End Sub

'Count Cells
Sub count_Cells()
Dim rng As Range
Set rng = Sheet2.Range("A1:C5").Cells
MsgBox "Total number of Cells:" & rng.count
End Sub

'Count Rows
Sub count_Rows()
Dim rng As Range
Set rng = Sheet1.Range("A1:C5").Rows
MsgBox "Total number of Rows:" & " " & rng.count
End Sub
The information provided on these pages remains, unless otherwise stated, the copyright of the respective authors. All layout, design, original graphics, co ncepts and
other World Wide Web Intellectual Property Rights barring the information mentioned above, remains the property and copy right of OrangeTree Global

'Count Columns
Sub count_columns()
Dim rng As Range
Set rng = Sheet1.Range("A1:C5").Columns
MsgBox "Total number of columns:" & " " & rng.count
End Sub

' Declaring an INTEGER variable, Finding the Sum, Displaying the answer in a Message Box
Sub sum_integer()
Sheet3.Activate
Dim a, b, total As Integer
a = Cells(1, 1).Value
b = Cells(2, 1).Value
total = a + b
'Cells(3, 1).Value = total
MsgBox "The sum total is :" & " " & total
End Sub

' Declaring an INTEGER variable, Finding the Sum, Displaying the answer in a Message Box
Sub sum_integer1()
Sheet3.Activate
Dim a, b, total As Integer
a = Cells(1, 1).Value
b = Cells(2, 1).Value
total = a + b
The information provided on these pages remains, unless otherwise stated, the copyright of the respective authors. All layout, design, original graphics, co ncepts and
other World Wide Web Intellectual Property Rights barring the information mentioned above, remains the property and copy right of OrangeTree Global

'Cells(3, 1).Value = total


MsgBox "The sum total is :" & " " & total
End Sub

' Declaring an DOUBLE variable, Finding the Sum, Displaying the answer in a Message Box
Sub sum_double()
Sheet3.Activate
Dim a, b, total As Double
a = Cells(1, 1).Value
b = Cells(2, 1).Value
total = a + b
'Cells(3, 1).Value = total
MsgBox "The sum total is :" & " " & total
End Sub

' Declaring an LONG variable, Finding the Sum, Displaying the answer in a Message Box
Sub sum_long()
Sheet3.Activate
Dim a, b, total As Long
a = Cells(1, 1).Value
b = Cells(2, 1).Value
total = a * b
'Cells(3, 1).Value = total
MsgBox "The sum total is :" & " " & total
End Sub

The information provided on these pages remains, unless otherwise stated, the copyright of the respective authors. All layout, design, original graphics, co ncepts and
other World Wide Web Intellectual Property Rights barring the information mentioned above, remains the property and copy right of OrangeTree Global

'Adding a comment
Sub addcomment()
Dim rng As Range
Dim c As comment
Set rng = Sheet1.Range("B2")
Set c = rng.addcomment("This is a comment")
End Sub

'Clearing a comment
Sub clearcomment()
Sheet1.Range("B2").ClearComments
End Sub

'Default autofill
Sub autofil_1()
Dim rng As Range
Set rng = Sheet2.Range("A1")
rng.Value = 2
rng.AutoFill Destination:=Range("A1:A6")
End Sub

'Default autofill series


Sub autofil_2()
Dim rng As Range
Set rng = Sheet2.Range("A1")
rng.Value = 2
The information provided on these pages remains, unless otherwise stated, the copyright of the respective authors. All layout, design, original graphics, co ncepts and
other World Wide Web Intellectual Property Rights barring the information mentioned above, remains the property and copy right of OrangeTree Global

rng.AutoFill Destination:=Range("A1:A6"), Type:=xlFillSeries


End Sub

'Default autofill Linear Trend


Sub autofil_3()
Dim rng As Range
Dim rng1 As Range
Set rng = Sheet2.Range("A1")
rng.Value = 2
Set rng1 = Sheet2.Range("A2")
rng1.Value = 4
Sheet2.Range("A1:A2").AutoFill Destination:=Range("A1:A6"), Type:=xlLinearTrend
End Sub

'Default Autofill with Growth Trend


Sub autofil_4()
Dim rng As Range
Dim rng1 As Range
Set rng = Sheet2.Range("A1")
rng.Value = 1
Set rng1 = Sheet2.Range("A2")
rng1.Value = 4
Sheet2.Range("A1:A2").AutoFill Destination:=Range("A1:A6"), Type:=xlGrowthTrend
End Sub

The information provided on these pages remains, unless otherwise stated, the copyright of the respective authors. All layout, design, original graphics, co ncepts and
other World Wide Web Intellectual Property Rights barring the information mentioned above, remains the property and copy right of OrangeTree Global

'Autofill with date value(day-wise increment)


Sub autofill_5()
Dim rng As Range
Set rng = Sheet3.Range("A1")
rng.Value = #1/1/2011#
Sheet3.Range("A1").AutoFill Destination:=Sheet3.Range("A1:A5"), Type:=xlFillSeries
End Sub

'Autofill with date value(month-wise increment)


Sub autofill_6()
Dim rng As Range
Set rng = Sheet3.Range("A1")
rng.Value = #1/1/2011#
Sheet3.Range("A1").AutoFill Destination:=Sheet3.Range("A1:A5"), Type:=xlFillMonths
End Sub

'Autofill with date value(year-wise increment)


Sub autofill_7()
Dim rng As Range
Set rng = Sheet3.Range("A1")
rng.Value = #1/1/2011#
Sheet3.Range("A1").AutoFill Destination:=Sheet3.Range("A1:A5"), Type:=xlFillYears
End Sub

Sub autofilter1()
Dim rng As Range
The information provided on these pages remains, unless otherwise stated, the copyright of the respective authors. All layout, design, original graphics, co ncepts and
other World Wide Web Intellectual Property Rights barring the information mentioned above, remains the property and copy right of OrangeTree Global

Set rng = Sheet3.Range("A1:h1")


rng.AutoFilter 3, "Lower Mid-Market"
'rng.AutoFilter 'remove autofilter
End Sub
'Autofilter

'Filtering 2 variables in the same column


Sub autofilter2()
Dim rng As Range
Set rng = Sheet3.Range("A1:l1")
rng.AutoFilter 3, "Lower Mid-Market", xlOr, "Government"
'rng.AutoFilter
End Sub

'Filtering two seperate columns


Sub autofilter3()
Dim rng As Range
Set rng = Sheet3.Range("A1:l1")
rng.AutoFilter 3, "Lower Mid-Market", xlOr, "Government"
rng.AutoFilter 4, "Kolkata"
'rng.AutoFilter
End Sub
Sub advfilter()
Sheet3.Range("A1:B12").AdvancedFilter xlFilterCopy, criteriarange:=Range("D1:E2"),
copytorange:=Range("F1")
End Sub
The information provided on these pages remains, unless otherwise stated, the copyright of the respective authors. All layout, design, original graphics, co ncepts and
other World Wide Web Intellectual Property Rights barring the information mentioned above, remains the property and copy right of OrangeTree Global

Sub advfilter1()
Sheet3.Range("A1:B12").AdvancedFilter xlFilterCopy, criteriarange:=Range("D1:E3"),
copytorange:=Range("J1")
End Sub
Function FirstOfNextMonth(dtmAny As Date) As Date
' This function calculates and returns the date of
' the first day of the month following the date passed by
' the argument.
' Note that this works even if Month(dtmAny) = 12.
FirstOfNextMonth = DateSerial(Year(dtmAny), Month(dtmAny) + 1, 1)
End Function
Sub paste_spl()
Sheet1.Activate
Range("E1:E206").Select
'Workbooks("Book1.xlsx").Worksheets("VBA Codes").Range("D3").Select
Selection.Copy
Worksheets("Sheet2").Select
Range("A1").Select
Selection.PasteSpecial Paste:=xlPasteValues
End Sub

Post Lunch Session


Sub chkformula()
Worksheets("Sheet1").Activate
Set rr = Application.InputBox( _
prompt:="Select a range on this worksheet", _
The information provided on these pages remains, unless otherwise stated, the copyright of the respective authors. All layout, design, original graphics, co ncepts and
other World Wide Web Intellectual Property Rights barring the information mentioned above, remains the property and copy right of OrangeTree Global

Type:=8)
If rr.HasFormula = True Then
MsgBox "Every cell in the selection contains a formula"
Else: MsgBox "No formula in the selected cell/cells"
End If
End Sub
Sub address()
Dim rng As Range
Set rng = Sheet1.Cells(1, 1)
MsgBox rng.address()
End Sub

Sub address1()
Dim rng As Range
Set rng = Sheet1.Cells(1, 1)
MsgBox rng.address(rowabsolute:=False)
End Sub

Sub address2()
Dim rng As Range
Set rng = Sheet1.Cells(1, 1)
MsgBox rng.address(rowabsolute:=False, columnabsolute:=False)
End Sub

The information provided on these pages remains, unless otherwise stated, the copyright of the respective authors. All layout, design, original graphics, co ncepts and
other World Wide Web Intellectual Property Rights barring the information mentioned above, remains the property and copy right of OrangeTree Global

Sub address3()
Dim rng As Range
Set rng = Sheet1.Cells(1, 1)
MsgBox rng.address(rowabsolute:=False, columnabsolute:=False, ReferenceStyle:=xlR1C1,
relativeto:=Sheet1.Cells(3, 3))
End Sub
Sub number_format()
Worksheets("Sheet1").Rows(1).NumberFormat = "dd/mm/yyyy"
End Sub

Sub number_format1()
Worksheets("Sheet1").Rows(2).NumberFormat = "$#,##0.00"
End Sub
Sub textproperty()
Set c = Worksheets("Sheet1").Range("B14")
c.Value = 1198
c.NumberFormat = "$#,##0_)"
MsgBox c.Value
MsgBox c.Text
End Sub
'Worksheet activation and giving color code to a range
Sub worksheet_property()
Worksheets("Sheet1").Range("A1:A10").Select
Selection.Interior.ColorIndex = 8
End Sub

The information provided on these pages remains, unless otherwise stated, the copyright of the respective authors. All layout, design, original graphics, co ncepts and
other World Wide Web Intellectual Property Rights barring the information mentioned above, remains the property and copy right of OrangeTree Global

Sub validation1()
Sheet2.Activate
Sheet2.Range("E1:E8").Select
With Sheet2.Range("E1:E8").Validation
'.Delete
.Add xlValidateWholeNumber, _
AlertStyle:=xlValidAlertStop, _
Operator:=xlBetween, _
Formula1:="5", Formula2:="10"
.IgnoreBlank = True
.ShowInput = True
.InputMessage = "enter value between 5 and 10"
.ShowError = True
.ErrorMessage = "pls enter valid no."
End With
End Sub

Sub validation2()
Sheet2.Activate
Sheet2.Range("E1:E8").Select
With Sheet2.Range("E1:E8").Validation
'.Delete
.Add xlValidateTextLength, _
AlertStyle:=xlValidAlertStop, _
Operator:=xlBetween, _
Formula1:="5", Formula2:="10"
The information provided on these pages remains, unless otherwise stated, the copyright of the respective authors. All layout, design, original graphics, co ncepts and
other World Wide Web Intellectual Property Rights barring the information mentioned above, remains the property and copy right of OrangeTree Global

.IgnoreBlank = True
.ShowInput = True
.InputMessage = "enter textlength between 5 and 10"
.ShowError = True
.ErrorMessage = "pls enter valid text"
End With
End Sub

Sub validation3()
Sheet2.Activate
With Sheet2.Range("A1:A10").Validation
.Add xlValidateList, AlertStyle:=xlValidAlertStop, Formula1:="=$B$1:$B$3"
.IgnoreBlank = True
.InCellDropdown = True
.ShowInput = True
.ShowError = True
.ErrorMessage = "Please enter values from the list"
End With
End Sub
'Sorting data set with one column (Cars.xls)
Sub sort()
Worksheets("My sheet").Range("A2:X206").sort _
key1:=Range("A2"), order1:=xlDescending
End Sub

The information provided on these pages remains, unless otherwise stated, the copyright of the respective authors. All layout, design, original graphics, co ncepts and
other World Wide Web Intellectual Property Rights barring the information mentioned above, remains the property and copy right of OrangeTree Global

'multiple sort(Cars.xls)
Sub sort_multiple()
Worksheets("My sheet").Range("A2:X206").sort _
key1:=Range("A2"), order1:=xlDescending, _
key2:=Range("H2"), order2:=xlAscending
End Sub
Sub selectcase()
Select Case Sheet2.Range("G1")
Case 100
Sheet2.Range("H1").Value = "A"
Case 200
Sheet2.Range("H1").Value = "B"
End Select
End Sub

Sub SelectCase1()
Sheet2.Activate
Select Case Range("A1").Value
Case 100 To 500
Range("B1").Value = Range("A1").Value
Case Else
Range("B1").Value = 0
End Select
End Sub

The information provided on these pages remains, unless otherwise stated, the copyright of the respective authors. All layout, design, original graphics, co ncepts and
other World Wide Web Intellectual Property Rights barring the information mentioned above, remains the property and copy right of OrangeTree Global

Sub SelectCase2()
Sheet2.Activate
Select Case Range("A1").Text
Case "Magma" To "OrangeTree"
Range("B1").Value = "it's between"
Case Else
Range("B1").Value = "it's not between"
End Select
End Sub
Sub formula()
Sheet1.Activate
Range("A1").Value = 200
Range("B1").Value = 0
Range("C1").formula = "=if(iserror(A1/B1),""NA"",A1/B1)"
End Sub

The information provided on these pages remains, unless otherwise stated, the copyright of the respective authors. All layout, design, original graphics, co ncepts and
other World Wide Web Intellectual Property Rights barring the information mentioned above, remains the property and copy right of OrangeTree Global

Potrebbero piacerti anche