You are on page 1of 13

1

infotica
vbafaculty@gmail.com

Operators
Operators are the special characters used to perform a predefined
task.
1 arithmetic : + - * /
\ - integer division (number without decimals)
eg : 13/2 = 6.5
13\2 = 6
^ : power
eg : 3^2 = 9
mod : returns remainder
eg : 13 mod 5 = 3

2. logical : And Or Not

3. Comparison : =,<>,<,<=,>,>=,Like (pattern match)

4. concatenation : & (ampersand) + (gives priority to SUM)


Note : '=' works like an assignment operator as well
Data Types
You should choose the data type that uses the smallest number of bytes but
can accommodate your data. Excel
provides characters you can use to set the data type for a variable. For
example, you can use the following syntax to
declare a string: Dim EmployeeName$.
DATA TYPE BYTES USED RANGE OF VALUE DECLARATION
CHARACTER
Boolean
2 bytes
True or False
Date
8 bytes

infotica
vbafaculty@gmail.com

1/1/100 to 12/31/9999
Double
(negative values)
8 bytes 1.79769313486231E308 to 4.9406564841247E324
#
Double
(positive values)
8 bytes
4.94065645841247E324 to 1.79769313486232E308
#
Integer
2 bytes
32,768 to 32,767
%
Long
4 bytes
2,147,483,648 to 2,147,483,647
&
Object
4 bytes
Any defined object
Single
(negative values)
4 bytes
3.402823E38 to 1.401298E-45
!
Single
(positive values)
4 bytes
1.401298E-45 to 3.402823E38
!
Note : Single & Double data types are used to work with decimal data
String
1 per character
Varies
$
Variant Varies Varies

Variables
A variable is a temporary memory location used by a program/programs to
store/retrieve/modify data
You use variables to store information for later use.
The following syntax stores information to a variable.

infotica
vbafaculty@gmail.com

VariableName = Value
VariableName represents the name you give to the variable. The equal sign

is the assignment operator.


The assignment operator tells VBA you want to assign something to a
variable. Value represents what you want
to assign to the variable. Once you assign a value to a variable, VBA
retrieves the assigned value whenever you
use the variable name. For example, you might make the following
assignment:
x=2

With this assignment, every time VBA sees the variable x, it interprets it to
mean 2. You can change the value
assigned to a variable many times and at any point in your code.

Variable Names :
You can name your variables anything you want; however, you must follow
these rules:
The first character of the variable name must be a letter.

Your variable name cannot include a space or any of the following: . ! @ &
$ or #.
Your variable name cannot exceed 255 characters.

Generally, you should not use names that are the same as functions,
statements, or methods.
Your variable name must be unique within its scope.
You do not need to start each word in your variable name with an
uppercase letter
If you develop a convention and use it consistently, you will have an easier
time debugging your code.

If you are making an assignment to a variable, you should start by declaring


the variable. In its simplest form, declaring your variable consists of telling
VBA what data type your variable will use. You can assign one of several
data types.
Generally, if your data consists of text or numbers you do not intend to use
in a mathematical calculation, you should declare your data as a string. If
your data is numerical data you do intend to use in mathematical
calculations, you should use one of the many numeric data types. Use the
data type that uses the least amount of bytes but fully accommodates your
needs. If you do not declare your variables, VBA assigns a variable type of
variant. A variant data type can hold any type of data. However, declaring
your variables makes your code run faster. You should declare your
variables.
You can declare a variable as procedure-only, module-only, or public.
You use a Dim statement to declare a procedure-only or module-only
variable. You type the word Dim followed by the variable name, the As
keyword, and then the variable type for example,

infotica
vbafaculty@gmail.com

Dim EmployeeName As String


If you are declaring a public variable, you replace the Dim keyword with
Public: Public EmployeeName As String.

After you have declared a variable, you assign a value to it. Type the
variable name, followed by an equal sign and
the value you want to assign the variable for example,
EmployeeName = Laxman Prasad .
If you do not declare a data type, VBA assigns the default data type of
variant. When a variable is a variant data type, VBA examines the variable to
determine if the value is an integer, string, date, Boolean, or other data type.
When you change the value assigned to the variable, VBA automatically
changes the data type if needed. For example, if you assign x = True, VBA
evaluates the expression and determines that x is a Boolean. If you later
change the assignment to x = Laxman, VBA reevaluates the expression and
determines x is a string. Having VBA evaluate your variables slows down
your code.
Option Explicit

When you declare a variable in VBA, you explicitly tell VBA the variables
data type. In other words, if your variable contains an integer, you declare an
integer variable. Because declaring a variable makes your code run faster
and more efficiently, you should make a habit of declaring variables. To
ensure that variables are always properly declared, type Option Explicit as
the first statement in your module. If Option Explicit is the first statement in
your module, your code does not run if you have any undeclared variables.
You must place the Option Explicit statement at the top of each module you
create.

Scope of variables
Each Excel workbook is a project. Each Sub procedure and function you
create is a procedure. You can place multiple procedures in a single module,
and you can have many modules in a project. VBA variables can be
procedure-only, module-only, or public. Only the procedure in which the
variable resides can use a procedure-only variable. Any procedure in a
module can use a module-only variable. Any procedure in a project can use
a public variable. Use the Dim statement to declare a procedure-only
variable. You place the statement after the Sub statement but before the
procedure code and End Sub statement in a Sub procedure. In a custom
function, you place the Dim statement after the Function statement but before
the procedure code and the End Function statement. The following example
includes several Dim statements that declare procedure-only variables:

Example:
Option Explicit
Sub ProcedureOnlyExample()
Dim EmpLastName As String
Dim Salary As Long
Dim StartDate As Date
Place procedure code here
End Sub

infotica
vbafaculty@gmail.com

When you want to create a module-only variable that any procedure in a


module can use, you place your declarations
before the first Sub or Function statement in the module. You refer to this
area of the module as the declarations area.
The example shown here includes several Dim statements used to declare
module-only variables.
Example:
Option Explicit
Dim EmpLastName As String
Dim Salary As Long
Dim StartDate As Date
Sub ModuleOnlyExample()
Place procedure-only declarations here.
Place procedure code here
End Sub

When you want to create a public variable that any procedure in your project
can use, you place your declarations in the declarations area before the first
Sub or Function statement in the module and precede them with the keyword
Public instead of Dim.
Example:
Option Explicit
Public EmpLastName As String
Public Salary As Long
Public StartDate As Date
Place module-only declarations here
Sub PublicVariableExample()
Place module-only declarations here.
Place procedure code here
End Sub

'Built-in Functions in VBA:


?ABS(-234.567)
234.567
?ASC("a")
97
?CHR(65)
A
?FIX(234.567) 'ONLY INTEGER PART
234
?LEN("ABC defg j123")

infotica
vbafaculty@gmail.com

13
?LEFT("ABC defg j123",5)
ABC d
?RIGHT("ABC defg j123",3)
123
?RIGHT("ABC defg j123",133)
ABC defg j123
'SYNTAX :MID(STRING,START,[LENGTH])
?MID("ABC defg j123",5) 'ALL CHARS FROM 5TH POSITION
defg j123

?MID("ABC defg j123",5,3) '3 CHARS FROM 5 TH POSITIOIN


def

?LCASE("ABC defg j123")


abc defg j123
?UCASE("ABC defg j123")
ABC DEFG J123

?StrConv("thIS IS vBA",vbProperCase)
This Is Vba

?LTRIM(" ABC
ABC

f23

f23 ")

infotica
vbafaculty@gmail.com

?len(LTRIM(" ABC

f23 "))

14

?len(RTRIM("ABC

f23 "))

11
?RTRIM("ABC
ABC

f23

?RTRIM("
ABC

?TRIM("
ABC

f23 ")

ABC

f23 ")

f23

ABC

f23 ")

f23

'CALLING AN EXCEL FUNCTION FROM VBA


?Application.WorksheetFunction.Trim("
ABC f23

'syntax : InSTR(start,string1,string2,compare)
'Finds the position of string2 in string1
'*It is case-sensitive
'*It returns 0 if string2 is not found

?InStr(1,"Oracle Corporate","Or")
1

ABC

f23 ")

infotica
vbafaculty@gmail.com

?InStr(1,"Oracle Corporate","or")
9

?InStr(1,"oracle Corporate","Or")
0

?InStr(1,"oracle Corporate","Or",vbTextCompare) 'def :


vbBinaryCompare
1

'replace(string,find,replace,compare:=compareoption)
'Named Argument : Name of the arugment for which a value
'is passed
'Note : := must be used after a named argument

?REPLACE("JACK AND JUE","J","BL")


BLACK AND BLUE

?REPLACE("JACK AND jUE","J","BL")


BLACK AND jUE

?REPLACE("JACK AND jUE","J","BL",compare:=vbTextCompare)


BLACK AND BLUE

infotica
vbafaculty@gmail.com

?ISNUMERIC(12.5)
True

?ISNUMERIC("12.5")
True
?ISNUMERIC("A12.5")
False
?ISNUMERIC("123A12.5")
False
?VAL("123A12.5")
123
?VAL("A12.5")
0
?SGN(12-100)
-1
?SGN(129-100)
1
?SGN(10-10)
0
?DATE 'SYSTEM SHORT DATE
7/24/2013

?FORMAT(DATE,"DDDDDD")
Wednesday, July 24, 2013

10

infotica
vbafaculty@gmail.com

?FORMAT(DATE,"dddd")
Wednesday
?FORMAT(DATE,"ddd")
Wed
?FORMAT(DATE,"dd")
24
?FORMAT(DATE,"d")
24

?FORMAT(DATE,"mmmm")
July

?FORMAT(DATE,"mmm")
Jul

?FORMAT(DATE,"mm")
07
?FORMAT(DATE,"m")
7

?FORMAT(DATE,"yyyy")
2013

?FORMAT(DATE,"yy")

11

infotica
vbafaculty@gmail.com

13

Write your first macro:


Open excel
Open vbe
Insert -> module
You can observe Module1 in the project explorer (ctrl+R)
Type SUB keyword, a space, the name of the macro & press <enter>
You can observe a blank set of () ,and End Sub
Write your code
Sub pro1()
Dim a As Integer 'declare
a = 10 'assign
'Basic Output function
'MSGBOX
'msgbox prompt,[buttons],[title]

12

infotica
vbafaculty@gmail.com

'msgbox "Are you ready?"


'MsgBox a

'f5 : to run a macro from vbe


'or click RUN button

'alt+f8 -> select the macro & click RUN


'(to run a macro from EXCEL)
MsgBox "The value of a is " & a
'Dim can declare one/more variables
'*Datatype is seperate for each variable

End Sub
Sub pro2()
'Dim a, b As Integer
'Note : b is an integer
'and a is a variant
Dim a As Integer, b As Integer
a = 10: b = 3
' : is used as a statement seperator to write
'more than one statement in a line
'operator ex:
MsgBox a + b
MsgBox a - b

13

infotica
vbafaculty@gmail.com

MsgBox a * b
MsgBox a / b
MsgBox a \ b
MsgBox a ^ b
MsgBox a Mod b
End Sub
Sub pro3()
'MsgBox "Are you ready?", vbYesNo + vbDefaultButton2 _
+ vbQuestion, "Ready?"

'vbQuestion vbExclamation vbCritical vbInformation


'line continuation character : space+_+ENTER

MsgBox "Are you ready?" & Chr(10) & "Click YES/NO", vbYesNo +
vbDefaultButton2 _
+ vbQuestion, "Ready?"
'vbNewLine vbCrLf
End Sub

You might also like