What is VBA - · PDF fileExcel VBA Terminologies The two main types of Procedures are Sub...
Transcript of What is VBA - · PDF fileExcel VBA Terminologies The two main types of Procedures are Sub...
What is VBA
VBA stands for Visual Basic for
Applications an event driven
programming language from Microsoft
that is now predominantly used with
Microsoft office applications such as
MS-Excel, MS-Word and MS-Access.
THINGS WE WILL COVER
In this Short Tutorial we will cover the
basics such as
How to Enable Developer Menu and
Accessing VBA Editor
Excel VBA Terminologies
Using VBA Loops
Using Range and Cells Object
Workbook and Worksheet Object
How to Enable Developer Menu
and Accessing VBA Editor
Accessing VBA Editor
In Excel window, press "ALT+F11". VBA
window opens as shown below.
How to Enable Developer Menu
and Accessing VBA Editor
First enable 'Developer' menu in Excel 20XX. To do the same, click on
File >> Options.
Step 2. Click Customize Ribbon Tab and check 'Developer' and click 'OK'.
How to Enable Developer Menu
and Accessing VBA Editor
The 'Developer' ribbon appears in menu
bar.
How to Enable Developer Menu
and Accessing VBA Editor
Now We can add as many Controls
such as Command Buttons and other
Controls as well
How to Enable Developer Menu
and Accessing VBA Editor
Now We can add as many Controls
such as Command Buttons and other
Controls as well
Excel VBA Terminologies
The two main types of Procedures are Sub and Function.
Function
A function is a group of reusable code which can be called anywhere in your program. This eliminates the need of writing same code over and over again. This will enable programmers to divide a big program into a number of small and manageable functions.
Apart from inbuilt Functions, VBA allows us to write user-defined functions as well and statements are written between Function and End Function
Sub Procedures
Sub Procedures work similar to functions while Sub procedures DONOT Return a value while functions may or may not return a value. Sub procedures Can be called without call keyword. Sub procedures are always enclosed within Sub and End Sub statements.
Using VBA Loops
‘For Loop
Private Sub CommandButton1_Click()
'For Loop
Dim a As Integer
a = 10
For i = 0 To a - 1 Step 1
MsgBox "The Value of i is " & i
Next
End Sub
‘For Each Loop
Private Sub CommandButton2_Click()
fruits = Array("Apple", "Orange", "Cherry", "Grape")
Dim fruitName As Variant
For Each Item In fruits
fruitName = "FruitName is " & Item
MsgBox fruitName
Next
End Sub
Using VBA Loops
'While Wend Loop
Private Sub CommandButton3_Click()
Dim Counter As Integer
Counter = 10
While Counter < 16
Counter = Counter + 1
MsgBox "Value of Counter is " & Counter
Wend
End Sub
'Do While Loop
Private Sub CommandButton4_Click()
Dim i As Integer
Do While i < 5
i = i + 1
MsgBox "The Value of i is" & i
Loop
End Sub
Using VBA Loops
‘Exit For Loop Private Sub CommandButton5_Click()
Dim i As Integer
i = 10
For k = 0 To i - 1 Step 1
MsgBox ("The Value of k is " & k)
If k = 4 Then
k = k * i
MsgBox ("Maximum Value Reached. k = " & k)
Exit For
End If
Next
End Sub
'Do Until Loop Private Sub CommandButton6_Click()
Dim i As Integer
i = 10
Do Until i > 15
i = i + 1
MsgBox ("The Value of i is " & i)
Loop
End Sub
Using Range Object
The Range object, which is the representation of
a cell (or cells) on your worksheet, is the most
important object of Excel VBA.
For Example:
Range("A1:A4").Value = 5
Range("A1:A2,B3:C4").Value = 10
Using Cells Object
Instead of Range, you can also use Cells. Using
Cells is particularly useful when you want to loop
through ranges.
For Example:
Cells(3, 2).Value = 2
Range(Cells(1, 1), Cells(4, 1)).Value = 5
Programming with Range and Cells
Dim example As Range Set example = Range("A1:C4") example.Value = 8
Select
An important method of the Range object is the Select method. The Select method simply selects a range.
Dim example As Range Set example = Range("A1:C4") example.Select
Programming with Range and Cells
Rows and Columns Property
The Rows property gives access to a specific row of a range
The Columns property gives access to a specific column of a range.
Dim example As Range
Set example = Range("A1:C4")
example.Rows(3).Select
example.Columns(2).Select
Programming with Range and Cells
Copy/Paste
The Copy and Paste method are used to copy a range and to paste it
somewhere else on the worksheet.
Range("A1:A2").Select
Selection.Copy
Range("C3").Select
ActiveSheet.Paste
Programming with Range and Cells
Clear
To clear the content of an Excel range, you can use the
ClearContents method.
Range("A1").ClearContents / Range("A1").Value = "“
Count
Dim example As Range
Set example = Range("A1:C4")
MsgBox example.Rows.Count
Workbook and Worksheet Object
The mother of all objects is Excel itself. We call it the Application object.
The application object contains other objects. For example, the
Workbook object (Excel file). This can be any workbook you have
created. The Workbook object contains other objects, such as the
Worksheet object. The Worksheet object contains other objects, such
as the Range object.
For Example:
Range("A1").Value = "Hello“
but what we really meant was:
Application.Workbooks(“Workbook-
Name").Worksheets(1).Range("A1").Value = "Hello"
You can refer to a member of the collection, for example, a
single Worksheet object, in three ways.
Using the worksheet name.
Worksheets("Sales").Range("A1").Value = "Hello“
Using the index number (1 is the first worksheet starting from
the left).
Worksheets(1).Range("A1").Value = "Hello”
Using the CodeName
Sheet1.Range("A1").Value = "Hello"
Workbook and Worksheet Object
Properties and Methods
The Add method of the Workbooks collection creates a new
workbook.
Workbooks.Add
The Count property of the Worksheets collection counts the
number of worksheets in a workbook.
MsgBox Worksheets.Count
Result when you click the command button on the sheet:
Workbook and Worksheet Object
For Loop in Excel Macros
Single Loop
Dim i As Integer For i = 1 To 6 Cells(i, 1).Value = 100 Next I
Double Loop
Dim i As Integer, j As Integer For i = 1 To 6 For j = 1 To 2 Cells(i, j).Value = 100 Next j Next i
Triple Loop
Dim c As Integer, i As Integer, j As Integer For c = 1 To 3 For i = 1 To 6 For j = 1 To 2 Worksheets(c).Cells(i, j).Value = 100 Next j Next i Next c
Besides the For Next loop, there are other loops as I have
conveyed earlier in Excel VBA. For example, the Do While
Loop. Code placed between Do While and Loop will be repeated
as long as the part after Do While is true.
Dim i As Integer
i = 1
Do While i < 6
Cells(i, 1).Value = 20
i = i + 1
Loop
Dim i As Integer
i = 1
Do While Cells(i, 1).Value <> ""
Cells(i, 2).Value = Cells(i, 1).Value + 10
i = i + 1
Loop
Do While in Excel Macros
Data Types Excel VBA data types can be grossly divided into two types, the
numeric data types and non-numeric data types. They are
classified below:
Numeric Data Types
Numeric data types are types of data that consist of numbers,
which can be computed mathematically with various standard
arithmetic operators such as add, minus, multiply, divide and so
on. In Excel VBA, the numeric data are divided into 7 types, which
are summarized in below table.
Non-numeric Data Types
The nonnumeric data types are summarized below:
Data Types
Data Type Storage Range
String(fixed length) Length of string 1 to 65,400 characters
String(variable length) Length + 10 bytes 0 to 2 billion characters
Date 8 bytes January 1, 100 to December 31,
9999
Boolean 2 bytes True or False
Object 4 bytes Any embedded object
Variant(numeric) 16 bytes Any value as large as Double
Variant(text) Length+22 bytes Same as variable-length string
Implicit Declaration
MyFirstName=“Sunayan"
MyAge=32
Excel VBA automatically create two variables MyFirstName and
MyAge as variants, and they are assigned data as Sunayan and 32
respectively. This type of declaration is called implicit declaration.
Explicit Declaration
Here Variables are normally declared in the general section of the
codes window using the Dim statement.
The syntax is as follows:
Dim variableName as DataType
Dim yourName As String
Dim firstnum As Integer
Dim BirthDay As Date
Data Types
Declaring Arrays in Excel VBA We use the Dim statement to declare an array just as the way we declare a single variable. In Excel VBA, we can have a one dimensional array, two dimensional array or even a multidimensional array (up to 60)
One Dimensional Array
The general statements to declare a one dimensional array in Excel VBA is as follows:
Dim arrayName(index) as dataType or
Dim arrayName(first index to last index) as dataType
For example,
Dim StudentName(10) as String
Dim StudentName(1 to 10) as String
Dim StudentMark(10) as Single
Dim StudentMark( 1 to 10) as Single
Example Private Sub CommandButton1_Click()
Dim StudentName(1 to 5) As String
For i = 1 To 5
StudentName(i) = InputBox("Enter student Name")
Cells(i, 1) = StudentName(i)
Next
End Sub
Declaring Arrays in Excel VBA
Private Sub CommandButton1_Click( )
Dim StudentName(3) As String, StudentID(3) As String,
StudentMark(3) As Single
For i = 1 To 3
StudentName(i) = InputBox("Enter student Name")
StudentID(i) = InputBox("Enter student ID")
StudentMark(i) = InputBox("Enter student Mark")
Cells(i, 1) = StudentName(i)
Cells(i, 2) = StudentID(i)
Cells(i, 3) = StudentMark(i)
Next
End Sub
Declaring Arrays in Excel VBA
Two Dimensional Array
The format to declare a two dimensional array is
Dim arrayName (num1, num2) as datatype
Dim Score (3, 3) as Integer
will create a two dimension array consists of 16 elements. These elements can be organized in a table form as shown in the table below
If you set the option base to 1, then there will be only 9 elements, i.e. from Score(1,1) to Score(3,3). However, if you want the first element to start with suffixes (1,1) you can also use the following format of declaration:
Dim Score(1 to 3, 1 to 3) as Integer
Declaring Arrays in Excel VBA
Score(0,0) Score(0,1) Score(0,2) Score(0,3)
Score(1,0) Score(1,1) Score(1,2) Score(1,3)
Score(2,0) Score(2,1) Score(2,2) Score(2,3)
Score(3,0) Score(3,1) Score(3,2) Score(3,3)
There are three kind of operators.
Arithmetic Operators
Comparison Operators
Logical Operators
Arithmetic Operator
Operators
Operator Mathematical function Example
^ Exponential MsgBox 2^4 gives a value of 16
* Multiplication MsgBox 4*3 gives a value of 12,
/ Division MsgBox 12/4 gives a value of 3
Mod
Modulus (returns the
remainder from an integer
division)
MsgBox 15 Mod 4 gives value of 3
\ Integer Division(discards
the decimal places) MsgBox 19\4 gives a value of 4
+ or & String concatenation
MsgBox "Excel"&"VBA 2010" or
"Excel"+"VBA 2010" produces a new
string "Excel VBA 2010"
Comparison Operators
Operators
Operator Meaning Example
< Less than
MsgBox 2<3 returns
true while MsgBox 4>5
returns false
<= Less than or equal to MsgBox 3<=4 returns
true
> Greater than MsgBox 5>4 returns
true
>= Greater than or equal to MsgBox 10>=9 returns
true
= Equal to MsgBox 10=10 returns
true
<> Not Equal to MsgBox 9<>10 returns
true
Logical Operators
Logical operators are also used in writing decision making
codes by comparing values or expressions.
Operators
Operator Meaning Example
And Logical Conjunction If A>=80 And B<101
thenGrade="A"
Or Logical Disjunction If income>5000 or car>2
thenStatus="Rich"
Not Logical negation MsgBox Not (3 >
4)returns true
Xor
Similar to Or, except
that it returns False if
both camparison values
are true
MsgBox 4 > 3 Xor 5 >2
returns false
Function and Sub
A function is a group of reusable code which can be called anywhere in your program. This eliminates the need of writing same code over and over again. This will enable programmers to divide a big program into a number of small and manageable functions.
Apart from inbuilt Functions, VBA allows us to write user-defined functions as well. Below Code will explain you how to write your own functions in VBA.
Function findArea(Length As Double, Optional Width As Variant)
If IsMissing(Width) Then
findArea = Length * Length
Else
findArea = Length * Width
End If
End Function
The Output of the area would be displayed to the user.
Function and Sub Sub Procedures
Sub Procedures are similar to functions but there are few differences.
Sub procedures DONOT Return a value while functions may or may not return a value.
Sub procedures Can be called without call keyword.
Sub procedures are always enclosed within Sub and End Sub statements.
Sub Area(x As Double, y As Double)
MsgBox x * y
End Sub
Function and Sub
Calling Procedures :
To invoke a Procedure somewhere in the script, you can
make a call from a function. We will not be able to use the
same way as that of a function as sub-procedure WILL NOT
return a value.
Function findArea(Length As Double, Width As Variant)
area Length, Width ' To Calculate Area 'area' sub proc is called
End Function
Sub Area(x As Double, y As Double)
MsgBox x * y
End Sub
There are three types of errors in programming:
Syntax Errors
Runtime Errors
Logical Errors.
Syntax errors, also called parsing errors, occur at interpretation
time for VBScript.
For Example: Function ErrorHanlding_Demo()
dim x,y x = "Tutorialspoint"
y = Ucase(x
End Function
The following line causes a syntax error because it is missing a closing
parenthesis.
Error/Exception Handling
Error/Exception Handling
Runtime errors
Runtime errors, also called exceptions, occur during execution, after interpretation.
For example, the following line causes a runtime error because here syntax is correct but at runtime it is trying to call fnmultiply, which is a non-existing function:
------------------------------------------------ Function ErrorHanlding_Demo1()
Dim x,y
x = 10
y = 20
z = fnadd(x,y)
a = fnmultiply(x,y)
End Function
------------------------------------------------------
Function fnadd(x,y)
fnadd = x+y
End Function
Error/Exception Handling Logical errors
Logic errors can be the most difficult type of errors to track
down. These errors are not the result of a syntax or runtime
error. Instead, they occur when you make a mistake in the
logic that drives your script and you do not get the result you
expected.
For example, dividing a number by zero or a script that is written
which enters into infinite loop.
Err Object
Assume if we have a runtime error, then the execution stops by
displaying the error message. As a developer, if we want to
capture the error, then Error Object is used.
Err.Number gives the error number and Err.Description
gives error description.
Error/Exception Handling
Public Sub OnErrorDemo()
On Error GoTo ErrorHandler ' Enable error-handling routine.
Dim x, y, z As Integer
x = 50
y = 0
z = x / y ' Divide by ZERO Error Raises
ErrorHandler: ' Error-handling routine.
Select Case Err.Number ' Evaluate error number.
Case 10 ' Divide by zero error
MsgBox ("You attempted to divide by zero!")
Case Else
MsgBox "UNKNOWN ERROR - Error# " & Err.Number & " : " & Err.Description
End Select
Resume Next
End Sub
Assignment
1. There is an Excel Sheet in the Following Workbook named "Assignment.xlsx"
2. You don't know the Count of rows or columns
3. You will have to create a button clicking upon which all the data should move to a new sheet with a message box saying relevant message
4. You have to save the newly created worksheet.
Userform Programming Open the Visual Basic
Editor. If the Project
Explorer is not visible,
click View, Project
Explorer.
Click Insert,
Userform. If the
Toolbox does not
appear
automatically, click
View, Toolbox. Your
screen should be
set up as below.
Userform Programming
.