VBA (Visual Basic For Applications)
VBA (Visual Basic For Applications)
VBA (Visual Basic For Applications)
The statements that should be executed by the macro follow the sub declaration and the macro ends
with an End Sub statement/keyword.
Sub MacroName()
[Statements]
End Sub
Objects, Properties & Methods
VBA is an Object Oriented Language – combination of different projects like Workbook, Worksheet,
Ranges, Charts, Pivots etc.
Object Model
Whenever you use Objects – you need to do so in an orderly manner.
For ex: If there is no workbook, a worksheet cannot exist, similarly, if there is no worksheet, a pivot
table or a graph cannot exist.
Workbook
Worksheet Object Model
Ranges/Pivots/Charts
A group of similar objects is called Collection. For ex: Collection of all workbook objects is referred
to as Workbook collections – similarly collection of all worksheet collections is referred to as
Worksheet collection
Objects, Properties & Methods contd..
All Objects have properties – a property can be thought of as a setting or an attribute. For ex:
Chart object has properties like ChartTitle, ChartType, Legend
Value Property – Using this property, we can set a value of a particular cell or can read the value
from a particular cell to a new variable
Examples:
New1 = Application.Workbooks("VBA File.xlsm").Worksheets("Sheet1"). Range("A1").Value
Worksheets("Sheet1").Range("A2").Value = New2
For ex: for the Range object we have Methods like ClearContents, Delete
‘Option Explicit’ should be used as it forces the user to declare all the variables beforehand
Rules –
Should not exceed 40 characters
No space
No special characters
Advantages –
Good Programing Standards
Removes chances of unexpected results by letting VBA know what a variable type is
Makes code more readable for other users
Type Range of Values
Integer -32,768 to 32,767
Long -2,147,483,648 to 2,147,483,648
Single -3.402823E+38 to -1.401298E-45 for negative values
1.401298E-45 to 3.402823E+38 for positive values
Double -1.79769313486232e+308 to -4.94065645841247E-324 for negative values
4.94065645841247E-324 to 1.79769313486232e+308 for positive values
Currency -922,337,203,685,477.5808 to 922,337,203,685,477.5807
Decimal +/- 79,228,162,514,264,337,593,543,950,335 if no decimal is use
+/- 7.9228162514264337593543950335 (28 decimal places)
Byte 0 to 255
String 1 to 65,400 characters
Date January 1, 100 to December 31, 9999
Boolean True or False
Some codes attached