Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
6 views61 pages

VBA in Excel

Uploaded by

deshmukhparth36
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views61 pages

VBA in Excel

Uploaded by

deshmukhparth36
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 61

VBA in Excel

VBA Stands for Visual Basic for Application. VBA is a programming


language that was developed by Microsoft Corp., and it is integrated into
the major Microsoft Office applications, such as Word, Excel, and Access.

What is Micro and VBA


Micro :
 A macro is a piece of code
 Macro are written in programming language I.e VBA

VBA :
 VBA is Visual Basic for Applications (Excel , Word , Power Point)
 VBA is editor in Excel , Word

VBA , VB and Vbs Difference


VB is stand alone program that runs independently
VBA is part of Excel Program and control work alone
Vbs is variant of Visual Basic Language used for internet Applications

Why Macros is required ?


Repetitive task
Develop new formulae
Complex Task

Synonyms for Macros.


Subroutine
Procedure
Program
About Macros
Macros is Object Oriented Program

In Excel , anything and everything is Object .


Ex. Workbook , Sheets , Cells , Charts etc.

Object Model for Excel


Application

Workbook

Worksheet

Range Charts Control Shape

Application : Application can be anything like Excel , Power Point etc


But here we are considering Excel is an application.

Workbook : Inside a Application there can be multiple Workbook.

Worksheet : Inside workbook there can be multiple worksheets.


Worksheet is nothing but a collection of cells . So here we will get
Rage,charts,Control and Shape. So it’s a Object Hierarchy.

Suppose we wants to call and range first of all we have to select a


Application then Workbook inside Workbook we will get worksheet and
then range.
User Interface Of Visual Basic for Application (VBA) Screen
If Developer option is not available in ribbon the follow steps :

Enable Developer Option in Excel

It hides the Developer tab on the ribbon by default. To customize the


ribbon, follow the steps mentioned below:

 Right-click on the ribbon (anywhere) click on the Customize the


Ribbon option.

 Go to Customize the Ribbon and select the Developer checkbox.

OR

 Go to File tab - Click on option - then click on customized ribbon -


check on developer option.
VBA Editor Interface

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.

Step 1 : Go to Developer Ribbon / Tab


Step 2 : Then go to Visual Basic

Step 3 : This kind of window will be open.


This window is called project window
This window will show name of the file and how many sheets are there it
will show. So here you can see file name is Book1 and there are only one
sheet is available.

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()

' first_procedure() MACRO name

MsgBox " Hello , Welcome To all of you in Excel Batch 4"

End Sub

' first_procedure() MACRO name - This is comment and whatever


procedure name we will give that is callled macro name because after
running tgis VBA code A macro will be created . In view macro you can
see.
Using the MsgBox we will get one one msgbox in excel sheet it will show
the msg " Hello , Welcome To all of you in Excel Batch 4". In msgbox you
can write whatever you want to print .

Let’s see the output :

** VBA - Macro Comments


Comments are used to document the program logic and the user
information with which other programmers can seamlessly work on the
same code in future.

It includes information such as developed by, modified by, and can also
include incorporated logic. Comments are ignored by the interpreter
while execution.

Comments in VBA are denoted by two methods.

Any statement that starts with a Single Quote (') is treated as comment.
Following is an example.

' This Script is invoked after successful login


' Written by : TutorialsPoint
' Return Value : True / False

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

** How to do Copy and Paste in VBA

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.

** How to give formatting to Cells value

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

'8 standard colors

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

' color index till 56


Range("a1:a10").font.ColorIndex = 1 ' Black
Range("a1:a10").font.ColorIndex = 10 ' green
Range("a1:a10").font.ColorIndex = 32 ' Blue

End Sub

Press F8 and see Line by Line execution.


You can use either font.color or colorIndex also. There are 1-56 color
index are available.

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

' color index till 56


Range("a1:a10").Interior.ColorIndex = 1
Range("a1:a10").Interior.ColorIndex = 10
Range("a1:a10").Interior.ColorIndex = 50
End sub

For Changing background color you have to used Interior.colorindex


because all the functionalities are comes under the Interior Group.

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.

The following example illustrates use of


the With statement to assign values to several properties
of the same object.

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

With Range("a1:a10").Borders - Will create the borders on this range. In


previous example we have seen we have written Borders every time
with their Objects but in with block we can write at once and whatever
Objects are there related with borders we can extract that all using only
dot(.) operator.

It will reduce our code and easy to learn.


In output you can see we are getting dashesh border with green color.

** Variable Declaration in VBA


Before moving to the VBA variable declaration, let us first understand
what variables are, the use of variables, and when we should use them.

What are the variables in VBA?

The word “variable” defines variables as the name of memory in your


location, which holds some value. You can pass a value in a code based
on the variable type. The value will be used while executing the code,
and you will get the output.

What is the use of Variable?

Creating a program or a code consists of instructions that pass the


information to the system about what to do with data. The data consist
of two types of values, fixed and variable. Fixed values are also called
“constant.” One may define variables by certain data types: Integer,
Byte, String, etc. It helps us to identify the nature of the data we are
entering, i.e., Text, Number, Boolean, etc.
How to Declare a Variable?

To declare a variable in code, you should assign a name to that variable.


You can assign any name to a variable. However, selecting a variable
name that relates to data is advisable so that other users can
understand it easily. For example, if you need to pass Integer data in the
code, then the name variables like i_count or out. If you need to pass a
string value, you can name that variable like strName.

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.

Variable is a named memory location used to hold a value that can be


changed during the script execution. Following are the basic rules for
naming a variable.

 You must use a letter as the first character.

 You can't use a space, period (.), exclamation mark (!), or the
characters @, &, $, # in the name.

 Name can't exceed 255 characters in length.

 You cannot use Visual Basic reserved keywords as variable name.

Syntax

In VBA, you need to declare the variables before using them.

Dim <<variable_name>> As <<variable_type>>

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.

Type Range of Values


Byte 0 to 255
Integer -32,768 to 32,767
Long -2,147,483,648 to 2,147,483,648
-3.402823E+38 to -1.401298E-45 for negative values
Single
1.401298E-45 to 3.402823E+38 for positive values.
-1.79769313486232e+308 to -4.94065645841247E-324
for negative values
Double
4.94065645841247E-324 to 1.79769313486232e+308
for positive values.
Currenc -922,337,203,685,477.5808 to
y 922,337,203,685,477.5807
+/- 79,228,162,514,264,337,593,543,950,335 if no
decimal is use
Decimal
+/- 7.9228162514264337593543950335 (28 decimal
places).

Non-Numeric Data Types

Following table displays the non-numeric data types and the allowed
range of values.

Type Range of Values


String (fixed length) 1 to 65,400 characters
String (variable length) 0 to 2 billion characters
Date January 1, 100 to December 31, 9999
Boolean True or False
Object Any embedded object
Variant (numeric) Any value as large as double
Variant (text) Same as variable-length string

Example

Let us create a button and name it as 'Variables_demo' to demonstrate


the use of variables.

Private Sub say_helloworld_Click()


Dim password As String
password = "Admin#1"

Dim num As Integer


num = 1234

Dim BirthDay As Date


BirthDay = DateValue("30 / 10 / 2020")

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:

1. First, declare the variable myValue of type Variant.

Dim myValue As Variant

Note: we use a variable of type Variant here because a Variant variable


can hold any type of value. This way the user can enter text, numbers,
etc.

2. Add the following code line to show the input box.

myValue = InputBox(“Give me some input”)

3. Write the value of myValue to cell A1.


Range(“A1”).Value = myValue

Result when the user enters the value 5 and clicks the OK button.

4. The InputBox function has more optional arguments. The following


code line shows an input box with a title displayed in the title bar and
has a default value. The default value will be used if no other input is
provided.

myValue = InputBox("Give me some input " , "Hi",1)

Result when the user only 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

In the example above, we are required to enter a number. If we enter a


number, then the variable dblAmount will put the number into the Excel
sheet at cell A1. However, if we do not enter a number, then a message
box will tell us that we did not enter a number and nothing will be put
into cell A1.

Ex.

Public Sub MyInputBox()


Dim MyInput As String
MyInput = InputBox("This is my InputBox")
If MyInput = "Enter You input text Here" Or MyInput = " " Then
Exit Sub
End If
MsgBox " The text from MyInputBox is " & MyInput
End Sub
** How to use Loops in VBA
Single Loop | Double Loop | Triple Loop | Do While Loop
Looping is one of the most powerful programming techniques.
A loop in Excel VBA enables you to loop through a range of cells with just
a few codes lines.
Single Loop
You can use a single loop to loop through a one-dimensional range of
cells.
Place a command button on your worksheet and add the following code
lines:
Dim i As Integer

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 i is lower than 6, Excel VBA enters the value 20


into the cell at the intersection of row i and column 1 and increments i
by 1. In Excel VBA (and in other programming languages), the symbol '='
means becomes. It does not mean equal. So i = i + 1 means i becomes i +
1. In other words: take the present value of i and add 1 to it. For
example, if i = 1, i becomes 1 + 1 = 2. As a result, the value 20 will be
placed into column A five times (not six because Excel VBA stops when i
equals 6).
2. Enter some numbers in column A.

3. Place a command button on your worksheet and add the following


code lines:
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
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 following error appears.

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 text1 & " " & text2


Result:

Note: to insert a space, use " "


Left
To extract the leftmost characters from a string, use Left.
Code:
Dim text As String
text = "example text"

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:

Note: space (position 8) included!


Instr
To find the position of a substring in a string, use Instr.
Code:
MsgBox Instr("example text", "am")
Result:

** Date and Time


Year, Month, Day of a Date | DateAdd | Current Date and Time | Hour,
Minute, Second | TimeValue
Learn how to work with dates and times 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.
Year, Month, Day of a Date
The following macro gets the year of a date. To declare a date, use the
Dim statement. To initialize a date, use the DateValue function.
Code:
Dim exampleDate As Date

exampleDate = DateValue("Jan 19, 2020")

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

firstDate = DateValue("Jan 19, 2020")


secondDate = DateAdd("d", 3, firstDate)

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:

Hour, Minute, Second


The get the hour of a time, use the Hour function.
Code:
MsgBox Hour(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:

Now, to clearly see that Excel handles times internally as numbers


between 0 and 1, add the following code lines:
Dim y As Double
y = TimeValue("09:20:01")
MsgBox y
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

To create a one-dimensional array, execute the following steps.Place


a command button on your worksheet and add the following code lines:

Dim Films(1 To 5) As String

Films(1) = "Lord of the Rings"


Films(2) = "Speed"
Films(3) = "Star Wars"
Films(4) = "The Godfather"
Films(5) = "Pulp Fiction"

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:

Dim Films(1 To 5, 1 To 2) As String


Dim i As Integer, j As Integer

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.

** VBA Code to Send Emails From Excel


In VBA, to send emails from Excel, we can automatically
automate our mailing feature to send emails to multiple users at a
time. However, to do so, we need to remember that we may do it
by outlook, another product of outlook, so we need to enable
outlook scripting in VBA. Once done, we use the .Application
method to use outlook features.
VBA’s versatility is just amazing. VBA coders love Excel because by using
VBA, we not only can work within Excel. Rather, we can also access other
Microsoft tools. For example, we can access PowerPoint, Word,
and Outlook by using VBA. So I was impressed when I heard of sending
emails from Excel. Yes, it is true. We can send emails from excel. This
article will show you how to send emails from Excel with
attachments using VBA Coding

Set Reference to Microsoft Office Library


We need to send emails from Outlook. Since Outlook is an external
objec, we first need object reference to “Microsoft Outlook 16.0
Object Library.”

In VBA, Go to Tools > References.

Now, we will see the object reference library. In this window,


we need to set the reference to “Microsoft Outlook 16.0
Object Library.”
After setting the object reference, click on “OK.”

Now, we can access Outlook objects in VBA coding.

Follow the below steps to write your first email excel macro.

Step #1

Start the sub procedure in VBA.

Code:

Sub SendEmail_Example1()

End Sub

Step #2
Declare the variable Outlook.Application

Code:

Dim EmailApp As Outlook.Application 'To refer to outlook application

Step #3

The above variable is an object variable. Therefore, we need to create an


instance of a new object separately. Below is the code to create a new
instance of the external object.

Code:

Set EmailApp = New Outlook.Application 'To launch outlook application

Step #4

Now, to write the email, we declare one more variable as


“Outlook.MailItem”.

Code:
Dim EmailItem As Outlook.MailItem 'To refer new outlook email

Step #5

To launch a new email, we need to set the reference to our previous


variable as “CreateItem.”

Code:

Set EmailItem = EmailApp.CreateItem(olMailItem) 'To launch new


outlook email

Now, the variable “EmailApp” will launch outlook. In the variable


“EmailItem,” we can start writing the email.

Step #6

We need to be aware of our items while writing an email. First, we need


to decide to whom we are sending the email. So for this, we need to
access the “TO” property.
Step #7

Enter the email ID of the receiver in double quotes.

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

After the CC, we can set the BCC email ID as well.

Code:

EmailItem.BCC = "[email protected]"

Step #10

We need to include the subject of the email we are sending.

Code:
EmailItem.Subject = "Test Email From Excel VBA"

Step #11

We need to write the email body using HTML body type.

Code:

EmailItem.HTMLBody = "Hi," & vbNewLine & vbNewLine & "This is my


first email from Excel" & _

vbNewLine & vbNewLine & _

"Regards," & vbNewLine & _

"VBA Coder" 'VbNewLine is the VBA Constant to insert a new


line
Step #12

We are working on if we want to add an attachment to the current


workbook. Then, we need to use the attachments property. First,
declare a variable source as a string.

Code:

Dim Source As String


Then in this variable, write ThisWorkbook.FullName after Email body.

Code:

Source = ThisWorkbook.FullName

In this VBA Code, ThisWorkbook is used for the current workbook


and .FullName is used to get the full name of the worksheet.

Then, write the following code to attach the file.

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()

Dim EmailApp As Outlook.ApplicationDim Source As StringSet EmailApp


= New Outlook.Application

Dim EmailItem As Outlook.MailItemSet EmailItem =


EmailApp.CreateItem(olMailItem)

EmailItem.To = "[email protected]"

EmailItem.CC = "[email protected]"

EmailItem.BCC = "[email protected]"
EmailItem.Subject = "Test Email From Excel VBA"

EmailItem.HTMLBody = "Hi," & vbNewLine & vbNewLine & "This is my


first email from Excel" & _

vbNewLine & vbNewLine & _

"Regards," & vbNewLine & _

"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 outlookApp As Object


Dim mail As Object

Set outlookApp = CreateObject("Outlook.Application")

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

MsgBox "Mails Send"

End Sub

You might also like