VBA in Excel
VBA in Excel
VBA :
VBA is Visual Basic for Applications (Excel , Word , Power Point)
VBA is editor in Excel , Word
Workbook
Worksheet
OR
You can open the VBA interface by using the ALT + F11 keyboard
shortcut, or you can go to the Developer tab and click on Visual Basic.
Suppose this widow is not appearing the you can go to view tab and click
on Project Explorer then you will get this same window.
After double clicking on sheet1 VBA code editor will be enable. I which
you can write the VBA code
This is Properties window here you can see all the properties regarding
worksheet.
In this insert tab you will get this options. Click on module so one
module will be inserted in project window.
Suppose you want’s to see which kind of Libraries are available in VBA
then go to View tab - Object Browser I this You can see all the classes
and which Objects are available there.
How to write a Program in VBA Editor
Step 1 : You have to create a procedure first that you can create from
insert tab also or you can create manually also.
Syntax :
Sub procedure name()
Statements 1
:
:
Statements n;
End
Create a MsgBox
Ex.
Sub first_procedure2()
End Sub
It includes information such as developed by, modified by, and can also
include incorporated logic. Comments are ignored by the interpreter
while execution.
Any statement that starts with a Single Quote (') is treated as comment.
Following is an example.
Cell Referencing
Cell referencing means here we can print whatever message we wants.
Ex.
Sub Cell_referencing()
ActiveCell.Value = "Excel"
ActiveCell.Value = 40
[b5].Value = 70
End Sub
So here you can see our cursor is on A2 cell means this is our Active cell.
So first It will print in A2 cell I.e Excel then it will override and it will
become 40
Suppose you want’s to write a value in any particular cell. so you can use
[b5].Value
Ex .
Sub Cell_referencing1()
ActiveCell.Value = "Excel"
ActiveCell.Value = 40
[b5].Value = 70
[c1:c10] = " Excel" ‘ From c1 to c10 will print Excel
Cells(8, 2).Value = "India" ‘ In 8 row and 2 column will print
India
Range("b1").Value = "Mumbai" ‘ In B1 print Mumbai
Range("a2:a10").Value = "Jakrta" ‘From A2 to A10 will print Jakrta
End Sub
Ex.
Sub copy_paste()
Range("a1:a10") = "Excel"
'1st Method
Range("b1:b10") = Range("a1:a10").Value
'2nd Method
Range("a1:a10").Copy
Range("d1:d10").Paste
Application.CutCopyMode = False ‘ Will stop dashes like
End Sub
Application.CutCopyMode = False : means after cut we will get dahsesh
line so it will remove that.
Sub font()
Range("a1:a10") = "Excel"
Range("a1:a10").font.Name = "Arial"
Range("a1:a10").font.Bold = True
Range("a1:a10").font.Size = 20
Range("a1:a10").font.Name = "Algerian"
Range("a1:a10").font.Name = "Arial"
Range("a1:a10").font.Size = 10
Range("a1:a10").font.Bold = True
Range("a1:a10").font.Bold = False
Range("a1:a10").font.Italic = True
Range("a1:a10").font.Italic = False
Range("a1:a10").font.Underline = True
Range("a1:a10").font.Underline = False
Range("a1:a10").font.Strikethrough = True
Range("a1:a10").font.Strikethrough = False
End Sub
We will Debug this code
In this code you can see
** How to use borders on range.
Ex.
Sub Borders()
Range("a1:a10").Borders.LineStyle = xlDot
Range("a1:a10").Borders.Color = vbGreen
Range("a1:a10").Borders.Weight = 3
Range("a1:a10").Borders.LineStyle = xlDot
Range("a1:a10").Borders.LineStyle = xlDash
Range("a1:a10").Borders.LineStyle = xlcountinuous
Range("a1:a10").Borders.LineStyle = xlDouble
End Sub
O/P :
Ex.
Sub alignment()
'Horizontal Alignment
Range("a1:d10").HorizontalAlignment = xlLeft
Range("a1:d10").HorizontalAlignment = xlRight
Range("a1:d10").HorizontalAlignment = xlCenter
'Vertical Alignment
Range("a1:d10").VerticalAlignment = xlTop
Range("a1:d10").VerticalAlignment = xlBottom
Range("a1:d10").VerticalAlignment = xlCenter
End Sub
O/P
Ex.
Sub font_color()
Range("a1:a10") = "Tutorials"
Range("a1:a10").font.Color = vbGreen
Range("a1:a10").font.Color = vbWhite
Range("a1:a10").font.Color = vbBlack
Range("a1:a10").font.Color = vbYellow
Range("a1:a10").font.Color = vbRed
Range("a1:a10").font.Color = vbGreen
Range("a1:a10").font.Color = vbBlue
Range("a1:a10").font.Color = vbmagneta
Range("a1:a10").font.ColorIndex = 1
End Sub
O/P :
Ex.
Sub cell_background_color()
Range("a1:a10") = "Tutorials"
Range("a1:a10").Interior.Color = vbRed
Range("a1:a10").Interior.ColorIndex = 1
'8 standard colors
Range("a1:a10").Interior.Color = vbWhite
Range("a1:a10").Interior.Color = vbBlack
Range("a1:a10").Interior.Color = vbYellow
Range("a1:a10").Interior.Color = vbRed
Range("a1:a10").Interior.Color = vbGreen
Range("a1:a10").Interior.Color = vbBlue
Range("a1:a10").Interior.Color = vbmagneta
Range("a1:a10").Interior.ColorIndex = 1
O/P :
With Block
The With statement allows you to perform a series of
statements on a specified object without requalifying the
name of the object. For example, to change a number of
different properties on a single object, place the property
assignment statements within the With control structure,
referring to the object once instead of referring to it with
each property assignment.
Ex.
Sub with_block_borders()
Range("a1:a10") = "Tutorials"
With Range("a1:a10").Borders
.LineStyle = xlDot
.Color = vbGreen
.Weight = 3
.LineStyle = xlDot
.LineStyle = xlDash
End With
End Sub
One can declare variables anywhere in the VBA Code. However, the
coder must declare them at the start of the code so that every user can
understand the code very easily. The variable should be declared using
Dim.
You can't use a space, period (.), exclamation mark (!), or the
characters @, &, $, # in the name.
Syntax
Data Types
There are many VBA data types, which can be divided into two main
categories, namely numeric and non-numeric data types.
Numeric Data Types
Following table displays the numeric data types and the allowed range
of values.
Following table displays the non-numeric data types and the allowed
range of values.
Example
MsgBox "Passowrd is " & password & Chr(10) & "Value of num is " &
num & Chr(10) & "Value of Birthday is " & BirthDayEnd Sub
Output
Upon executing the script, the output will be as shown in the following
screenshot.
Ex :
Sub VBA_Code1()
Dim SCore As Ineger
Score = 101
MsgBox “Sachin Scored “ & Score
End Sub
Ex :
Sub VBA_Code_String()
Dim strName As String
strName = “Ram”
Range(“A1:A10) = “Ram”
End Sub
Ex.
Sub variable()
Dim country As String
country = "India"
ActiveCell.Value = country
End Sub
Ex.
Sub if_condition()
Dim country As String
country = " India"
If country = " USA" Then
ActiveCell.Value = " Welcome in India"
Else
ActiveCell.Value = " Hello"
End If
End Sub
** InputBox Function
You can use the InputBox function in Excel VBA to prompt the user to
enter a value. Place a command button on your worksheet and add the
following code lines:
Result when the user enters the value 5 and clicks the OK button.
Ex.
Sub EnterNumber()
On Error Resume Next
Dim dblAmount As Double
dblAmount = InputBox("Please enter the required amount")
If dblAmount <> 0 Then
Range("A1") = dblAmount
MsgBox dblAmount
Else
MsgBox "You did not enter a number!"
End If
End Sub
Ex.
For i = 1 To 6
Cells(i, 1).Value = 100
Next i
Result when you click the command button on the sheet:
Explanation: The code lines between For and Next will be executed six
times. For i = 1, Excel VBA enters the value 100 into the cell at the
intersection of row 1 and column 1. When Excel VBA reaches Next i, it
increases i with 1 and jumps back to the For statement. For i = 2, Excel
VBA enters the value 100 into the cell at the intersection of row 2 and
column 1, etc.
Note: it is good practice to always indent (tab) the code between the
words For and Next. This makes your code easier to read.
Double Loop
You can use a double loop to loop through a two-dimensional range of
cells.
Place a command button on your worksheet and add the following code
lines:
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
Result when you click the command button on the sheet:
Explanation: For i = 1 and j = 1, Excel VBA enters the value 100 into the
cell at the intersection of row 1 and column 1. When Excel VBA reaches
Next j, it increases j with 1 and jumps back to the For j statement. For i =
1 and j = 2, Excel VBA enters the value 100 into the cell at the
intersection of row 1 and column 2. Next, Excel VBA ignores Next j
because j only runs from 1 to 2. When Excel VBA reaches Next i, it
increases i with 1 and jumps back to the For i statement. For i = 2 and j =
1, Excel VBA enters the value 100 into the cell at the intersection of row
2 and column 1, etc.
Triple Loop
You can use a triple loop to loop through two-dimensional ranges on
multiple Excel worksheets.
Place a command button on your worksheet and add the following code
lines:
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
Explanation: The only change made compared to the code for the
double loop is that we have added one more loop and added
Worksheets(c). in front of Cells to get the two-dimensional range on the
first sheet for c = 1, the second sheet for c = 2 and the third sheet for c =
3. Download the Excel file to see this result.
Do While Loop
Besides the For Next loop, there are other loops 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.
1. Place a command button on your worksheet and add the following
code lines:
Dim i As Integer
i=1
Do While i < 6
Cells(i, 1).Value = 20
i=i+1
Loop
Result when you click the command button on the sheet:
Explanation: as long as Cells(i, 1).Value is not empty (<> means not equal
to), Excel VBA enters the value into the cell at the intersection of row i
and column 2, that is 10 higher than the value in the cell at the
intersection of row i and column 1. Excel VBA stops when i equals 7
because Cells(7, 1).Value is empty. This is a great way to loop through
any number of rows on a worksheet.
Ex.
Sub Loop1()
Dim i As Integer
i=1
Do While i <= 15
If ActiveCell.Value > 100 Then
ActiveCell.Interior.Color = vbRed
End If
ActiveCell.Offset(2, 0).Select
i=i+1
Loop
End Sub
O/P
Explaination :
Dim i as Integer - Here we declare a variable I.e I it contains numerical
values.
i=1 - We initialized I values it’s 1.
Do While loop - it will execute till i value will be 15.
So here we first given some values in range from A1 : A15
In the if condition we have written If ActiveCell.Value > 100 then so we
can see in the output from only those cell is highlighted which has
values is more that 100.
In the else part we will goes to
Activecell.offset(1,0).select - 1 Mean it will jump to next row and 0
means column so it will stay on same column but it will jump one by one
on next row .
i = i + 1; - it will increased the I value by 1.
** Macro Errors
This chapter teaches you how to deal with macro errors in Excel. First,
let's create some errors.
Place a command button on your worksheet and add the following code
lines:
x=2
Range("A1").Valu = x
1. Click the command button on the sheet.
Result:
2. Click OK.
The variable x is not defined. Because we are using the Option
Explicit statement at the start of our code, we have to declare all our
variables. Excel VBA has colored the x blue to indicate the error.
3. In the Visual Basic Editor, click Reset to stop the debugger.
4. Correct the error by adding the following code line at the start of the
code.
Dim x As Integer
You may have heard of the technique called debugging before. With this
technique you can step through your code.
5. In the Visual Basic Editor, place your cursor before Private and press
F8.
The first line turns yellow.
6. Press F8 three more times.
The Range object has a property called Value. Value isn't spelled
correctly here. Debugging is a great way to not only find errors, but also
understand code better. Our Debugging example program shows you
how to single step through your code and see the effect of each code
line on your worksheet.
** String Manipulation
Join Strings | Left | Right | Mid | Len | Instr
In this chapter, you'll find the most important functions to manipulate
strings in Excel VBA.
Place a command button on your worksheet and add the code lines
below. To execute the code lines, click the command button on the
sheet.
Join Strings
We use the & operator to concatenate (join) strings.
Code:
Dim text1 As String, text2 As String
text1 = "Hi"
text2 = "Tim"
MsgBox Left(text, 4)
Result:
Right
To extract the rightmost characters from a string, use Right. We can also
directly insert text in a function.
Code:
MsgBox Right("example text", 2)
Result:
Mid
To extract a substring, starting in the middle of a string, use Mid.
Code:
MsgBox Mid("example text", 9, 2)
Result:
Note: started at position 9 (t) with length 2. You can omit the third
argument if you want to extract a substring starting in the middle of a
string, until the end of the string.
Len
To get the length of a string, use Len.
Code:
MsgBox Len("example text")
Result:
MsgBox Year(exampleDate)
Result:
Note: Use Month and Day to get the month and day of a date.
DateAdd
To add a number of days to a date, use the DateAdd function. The
DateAdd function has three arguments. Fill in "d" for the first argument
to add days. Fill in 3 for the second argument to add 3 days. The third
argument represents the date to which the number of days will be
added.
Code:
Dim firstDate As Date, secondDate As Date
MsgBox secondDate
Result:
Note: Change "d" to "m" to add a number of months to a date. Place
your cursor on DateAdd in the Visual Basic Editor and click F1 for help on
the other interval specifiers. Dates are in US Format. Months first, Days
second. This type of format depends on your windows regional settings.
Current Date and Time
To get the current date and time, use the Now function.
Code:
MsgBox Now
Result:
Note: Use Minute and Second to get the minute and second of a time.
TimeValue
The TimeValue function converts a string to a time serial number. The
time's serial number is a number between 0 and 1. For example, noon
(halfway through the day) is represented as 0.5.
Code:
MsgBox TimeValue("9:20:01 am")
Result:
** Array
One-dimensional Array | Two-dimensional Array
An array is a group of variables. In Excel VBA, you can refer to a specific
variable (element) of an array by using the array name and the index
number.
One-dimensional Array
MsgBox Films(4)
Result when you click the command button on the sheet:
Explanation: the first code line declares a String array with name Films.
The array consists of five elements. Next, we initialize each element of
the array. Finally, we display the fourth element using a MsgBox.
Two-dimensional Array
To create a two-dimensional array, execute the following steps. This
time we are going to read the names from the sheet.
Place a command button on your worksheet and add the following code
lines:
For i = 1 To 5
For j = 1 To 2
Films(i, j) = Cells(i, j).Value
Next j
Next i
MsgBox Films(4, 2)
Result when you click the command button on the sheet:
Explanation: the first code line declares a String array with name Films.
The array has two dimensions. It consists of 5 rows and 2 columns. Tip:
rows go first, then columns. The other two variables of type Integer are
used for the Double Loop to initialize each element of the array. Finally,
we display the element at the intersection of row 4 and column 2.
Follow the below steps to write your first email excel macro.
Step #1
Code:
Sub SendEmail_Example1()
End Sub
Step #2
Declare the variable Outlook.Application
Code:
Step #3
Code:
Step #4
Code:
Dim EmailItem As Outlook.MailItem 'To refer new outlook email
Step #5
Code:
Step #6
Code:
EmailItem.To = "[email protected]"
Step #8
After addressing the main receiver, if you would like to CC anyone in the
email, we can use the “CC” property.
Code:
EmailItem.CC = "[email protected]"
Step #9
Code:
EmailItem.BCC = "[email protected]"
Step #10
Code:
EmailItem.Subject = "Test Email From Excel VBA"
Step #11
Code:
Code:
Code:
Source = ThisWorkbook.FullName
Code:
EmailItem.Attachments.Add Source
Step #13
Finally, we need to send the email to the mentioned email IDs. We can
do this by using the “Send” method.
Code:
EmailItem.Send
We have completed the coding part.
Code:
Ex.1
Sub SendEmail_Example1()
EmailItem.To = "[email protected]"
EmailItem.CC = "[email protected]"
EmailItem.BCC = "[email protected]"
EmailItem.Subject = "Test Email From Excel VBA"
"VBA Coder"
Source = ThisWorkbook.FullName
EmailItem.Attachments.Add Source
EmailItem.Send
End Sub
Ex. 2
Sub send_multiple_email()
Dim w As Worksheet
Set w = ThisWorkbook.Sheets("Sheet1")
Dim i As Integer
Dim n As Integer
n = Application.WorksheetFunction.CountA(w.Range("A:A"))
For i = 2 To n
Set mail = outlookApp.createitem(0)
mail.to = w.Range("A" & i).Value ' A2
mail.cc = w.Range("B" & i).Value ' B2
mail.Subject = w.Range("C" & i).Value ' C2
mail.Body = w.Range("D" & i).Value ' D2
mail.display
mail.send
Next i
End Sub