Sei sulla pagina 1di 51

VBA with Excel

Recording Your First Macro


You can use Excel buildbuild-in macro recorder to
translates your actions into VBA macro
commands. After you recorded the macro, you
will be able to see the VBA code in the Module
window. Before you record a macro, plan the
steps and commands that you want the macro
to perform. Every action that you take during
the recording of the macro will be recorded including the correction that you made.

Steps to Record a Macro


Tools Menu

Macro command

Record New macro

Assign a name for macro/ShortCut key

After Recording STOP the macro

Lets record a Macro which types the following in columns A, B & C


and from Rows 1 to 6.
Lets format the first row as heading

Record a Macro for typing the following and then applying the
formulas written below
A

S.No

Name

Marks

Amit

56

Kamal

67

Namrata

68

Deepti

59

Yogesh

78

Use the following formulas


1. Cell D1=Average Marks
2. Cell E1=Total Students
3. Cell F1=Count of Students who have scored above 65
Now copy the paste the values only.

Steps to Run a Macro


Tools Menu

Macro command

Macros/Alt+F8

Select the Macro Name

Run Button

Programming
Nowadays computer programming has become
much easier, and even soso-called normal people
now engage in this activity. Programming
simply means developing instructions that the
computer automatically carries out.
Excel programming means that you can instruct
Excel to automatically do things that you
normally do manually saving you lots of time
resources.

About VBA
VBA is the best thought of as Microsofts
common application.
It is included with most of the Office 2003
applications.
You will be able to write macros for other
Microsoft products.

Basics of VBA
Code: You can perform actions in VBA by
executing VBA code. You write ( or
record) VBA Code which is stored in a VBA
Module.
Module: VBA Modules are stored in a
Excel workbook, but you can view and edit
a module by using Visual basic Editor
(VBE).

VBE
The Visual Basic Editor is a separate
application where you write and edit your
VBA macros. It works seamlessly with
Excel. You can activate the VBE
by pressing Alt+F11 when Excel is active
or by using the Tool
Tool--Macro
Macro--Visual Basic
Editor command.
command.

Parts of VBE Window


Menu Bar
Project Explorer
Code Window
Object Browser
Properties Window
Immediate Window

Parts of VBE Editor


Menu Bar

Project
Explorer

Properties
Window

Code
Window

Project Explorer
The Project Explorer window displays a tree
diagram that shows every workbook currently
open in Excel (including addadd-ins and hidden
workbooks). When youre working in the VBE,
each Excel workbook and addadd-in thats open is a
project. You can think of a project as a collection
of objects arranged as an outline. Click on the
plus sign (+) at the left of the projects name in
the Project Explorer window to expand a project.

Code Window
The VBA code is contains in the Code
window. Every object in a project has an
associated Code window. DoubleDouble-click the
object in the Project Explorer window to
bring up the Code Window. For example,
to view the Code window for the Sheet1
object, double
double--click Sheet1 in the Project
Explorer window.
window. Unless youve added
some VBA code, the Code window will be
empty.

Object Browser

The VBE includes another tool, known as the Object Browser. This
tool allows you browse through the objects available to you. To
access the Object Browser, press F2 when the VBE is active (or
choose View
Object Browser).

Object
Browser

Properties Window
This window is
used to show/Edit
properties of the
selected object in
the current project.
eg: Name, Height,
Font, Enable,
Visible etc.

Immediate Window
The Immediate window is the most useful for executing
VBA statements directly testing statements, and
debugging your code. This window might or might not
be visible. If the Immediate window is not visible then
press CTRL+G. To close click the Close button in its title
bar or right click anywhere in Immediate Window and
select Hide from the shortcut menu.

Immediate
Window

Basics of VBA
Module

Procedures

Sub-Procedure

Function-Procedure

Sub--Procedure
Sub
A Sub procedure consists of a series of
statements and can be executed in
number of ways.
Eg: Sub Test ()
Sum=1+1
Msgbox the answer is & Sum
End Sub

Function--Procedure
Function
Function: A VBA Module can also have
Function procedures. A Function
procedure returns a single value. A
Function can be called from another VBA
procedure or used in a worksheet formula.
Eg: Function AddTwo ( arg1, arg2)
AddTwo = arg1 + arg2
End Function

Top--Level Excel Objects


Top
Application

WorkBooks

WorkBook

Sheets

Worksheet

Range

What is Variable
A Variable is simply a named storage
location in your computers memory.
Variables can accommodate a wide variety
of data types from simple Boolean to
large, precision values. You can assign a
value to a variable by using an equal sign
operator.
Eg: name=Ajay , amt=4500

There are few rules to be followed


regarding variable names:
You can use alphabetic characters, numbers, and some punctuation
characters, but the first character must be alphabetic
VBA does not distinguish between case. To make variables more
readable programmers often use mixed case.
You cannot use spaces or periods. To make variables more
readable, programmers often use underscore character.
Special type declaration characters (#, %, $, & or |) cannot be
embedded in a variable.
Variables name can be as long as 254 characters but using such
long names is not recommended.

Data Types
When a data type is
declared it means
that you have define
the kind of value that
may be stored within
the memory allocated
for a variable. There
are many data types

VBA BUILT-IN DATA TYPES


Data Type

BytesUsed

Range of Values

Boolean

2 Bytes

True or False

Integer

2 Bytes

-32,768 to 32,767

Long

4 Bytes

-2,147,483,648 to 2,147,483,647

Date

8 Bytes

Jan 1 0100 to Dec 31, 9999

String

Lengthof
String

1 to 65,400 characters

Variant

16 Bytes

Any numeric value, it can also


hold
NULL, Error
and
Nothing

Common Math Operators Used


In VBA
Addition
Subtraction
Multiplication
Division
Exponential

+
*
/
^

Numeric Data Type


You can be performed any mathematical
operation on a numerical variable. The following
are a few examples:
Dim num1 As Integer
Dim num2 As Integer
Dim answer As Integer
num1 = 4
num2 = 2
answer = num1 + num2 answer Holds 6
answer = num1 - num2 answer Holds 2
answer = num1 * num2 answer Holds 8
answer = num1 / num2 answer Holds 2
answer = num1 ^ 2 answer Holds 16
answer = 2 ^ num2 answer Holds 4

Numerical Data Types


The numerical data types are integer, long, single, and
double. If you declare a variable as an integer or long
data type, it only can hold whole numbers or non
non-fractional values within the specified ranges. It cannot
hold fractional or floating point values. For fractional or
floating point values use a single or double data type.
Note:-Note:
Pay attention to the value of the number that you
declare within the variable. If the value gets too large for
the data type, your program will crash.

String Data Types


To hold characters as text, the variables are declared as
string data types . A string data type can hold can be
numbers, letters, or special symbols (for example,
punctuation marks). Basically, just about anything you
can type on your keyboard can be held within a string
variable. To do this, use the String keyword like the
example below.

Eg:
Dim myName As String
myName = Peter Anderson

Working with Dates


You can use a string variable to store a date, but
if you do it is not a real date (meaning you cant
perform calculations). Using the Date data type
is a better way to work with dates.
A variable defined as date occupies 8 bytes of
storage and can hold dates from Jan 1, 0100 to
Dec 31, 9999. The Date type data is also used
for storing timetime-related data. In VBA, you
specify date and times by enclosing them
between 2 hash marks (#).

Working with Dates


Dim Today as Date
Dim LastTime As Date =# 6/6/2007# here the variable is a fix date
Dim NumDay As Integer
Today = Now
NumDay = Today LastTime
When you run the code, NumDay will stored the numbers of days that
have elapsed since he 6/6/07. Thus, the date data type gives your
routines greater flexibility.
In VBA, place dates and times between two hash marks, as shown in
the above examples.
Date variables display dates according to your systems short date
format, and display times according to your systems time format (either
12-- or 24
12
24--hour) so it depends on the settings for the system on which
the application is running.

Variant Data Types


Variant data types are comparable to the General category in the
number format of a spreadsheet cell in the Excel application.
You can use Variant type variables to hold any type of data except a
fixed length string. This way Variant data types give the
programmer more flexibility; but if overused, they can be dangerous
and slow down program execution. It is not advisable to use them
due to reason given above.
Eg:
Dim myVar As Integer
myVar = 5
myVar = Five

Simple Input and Output with


VBA
You already know how to get input from the user
through the use of the Value property of a spreadsheet
cell.
Eg: Activecell.value
Apart from that, you can also generate output for the
user through the spreadsheet. However there may be
times when you want something more dynamic and
dramatic way to interact with the user than using a
spreadsheet cell. The most common method for
gathering input from the user and sending output back is
the InputBox() and MsgBox() functions.

Collecting User Input with


InputBox()
The InputBox() function can be used to
prompt and sometime to force a response
from the user.
Eg: Dim MyInput
MyInput = InputBox("Enter your name")

Output with MsgBox()


Outputs a message to the user or ask a
question that require a yes / no answer.
This is also useful as a way to inform the
user about some type of problem.
MsgBox(prompt[, buttons] [, title] [,
helpfile, context])

Output with MsgBox()


You can choose to display an icon
(warnings or information type), a help
button, and add some additional
formatting with your choice of buttons.
Eg: Msg = MsgBox(How Are You,
vbOKOnly, Message)

Relational operators
=
<>
<
>
<=
>=

Tests for equality


Tests for inequality
Less than
Greater than
Less than or equal to
Greater than or equal to

Truth table
AND
Condition1
True
True
False
False

Condition2

Condition1 AND Condition2

True
False
True
False

True
False
False
False

Here both condition1 and condition2 has to be satisfied.


OR
Condition1
True
True
False
False

Condition2
True
False
True
False

Condition1 OR Condition2
True
True
True
False

Here either condition1 or condition2 has to be satisfied.


NOT
Condition1
True
False

NOT Condition1
False
True

Write a procedure which takes an Input from the user. Increments


it by 20% & displays the result in a Message Box

Lets create a procedure, which uses the nSum Variable and


displays the sum of three numbers entered by the user through a
Message Box

Conditionals and Branching


If/Then/Else structure is known as both a conditional and
branching structure because it uses conditional statements to
change the flow or direction of program execution.
Syntax:
If (condition) Then
Block of code statements
End If

Eg:
If (userGuess <> answer) Then
MsgBox (Wrong! The answer is & answer)
Else
MsgBox (You got it!)
End If

ElseIf clause
Another option regarding If/Then/Else structures is the ElseIf clause. The ElseIf
clause is used like the Else clause with a conditional expression. You can use the
if...then...elseif statement if you want to select one of many blocks of code to
execute: Look at the example below,

Private Sub Greeting()


Dim theHour As Integer
theHour =hour(time)
If theHour = 9 then
MsgBox("Just started...!")
elseif theHour = 11 then
MsgBox ("Hungry!")
elseif theHour = 12 then
MsgBox ("Ah, lunch-time!")
elseif theHour = 17 then
MsgBox ("Time to go home!")
else
end if

MsgBox ("Unknown")

Create a procedure in VBA, which accepts Employee name &


Salary for two people from the user
It finds the average salary & displays that in the message box

Lets create a procedure that reads the value in the cell A4, and puts
the same value in the cell A5

Lets create a procedure that changes the value in the cell B9 to the
current time every time you click on the button.

Create a button on Sheet1 and add sheet specific code in such a


way that every time the sheet is selected you see a welcome
message.

Create a workbook specific code so that every time you open the
excel file you are getting a welcome message and every time you
are closing this file you are getting a bye message

Lets create a procedure which change the color of the cell based on
the value selected in it. Just like conditional formatting

Write a procedure which displays the Full Name as follows


Last Name , First Name - If Last name is not blank

First Name

For the following data:


SNo
FirstName
Name
1
Amit
2
Deepak
3
Ajay
4
Payal
5
Deepak

- If Last name is blank

LastName

Full

Gupta

?
?
?
?
?

Sharma
Mehta

Lets create a form like this, which has a button once you click on
the button a message is displayed on the screen

Create a form like this which appears every time you open the file

Name
:
Manish Beniwal
Mobile no.
:
9891242247
Email
:
manishsinghbeniwal@yahoo.com

Potrebbero piacerti anche