Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
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 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
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
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
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.
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
' 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
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 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
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
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