You are on page 1of 35

1

WORKING WITH
VARIABLES
ELF © 2013
Excel VBA
Concept of Variables
2

 Variables are areas allocated by the computer memory to


hold data.
 Declared using the Dim command
 Example
Dim Something

 Variable Names
 The following are the rules when naming the variables in VBA
 It must be less than 255 characters
 No spacing is allowed
 It must not begin with a number
 Period is not permitted
Concept of Variables
3

 Declaring Variables
 Needs to declare the variables before using them by
assigning names and data types.
 Format syntax:
 Dim variable_name As data_type

 There are many VBA data types, which can be grossly


divided into two types:
 numericdata types
 non-numeric data types
Data Types
4

 Data Types
 The manner in which a program stores data in memory.
 The type of data a variable is classified as

 The good thing - VBA can take care of this


automatically
 The bad thing - Letting VBA handle your data typing
results in slower execution and inefficient memory use
Data Types
5

 Numeric Data Types


 Consist of numbers, which can be computed mathematically with various
standard operators such as add, minus, multiply, divide and so on.

Data Type Storage Range of Values


Byte 1 byte 0 to 255

Integer 2 bytes -32,768 to 32,767

Long 4 bytes -2,147,483,648 to 2,147,483,648

Single 4 bytes -3.402823E+38 to -1.401298E-45 for negative values


1.401298E-45 to 3.402823E+38 for positive values.
Double 8 bytes -1.79769313486232e+308 to -4.94065645841247E-324 for negative values
4.94065645841247E-324 to 1.79769313486232e+308 for positive values.

Currency 8 bytes -922,337,203,685,477.5808 to 922,337,203,685,477.5807

Decimal 12 bytes +/- 79,228,162,514,264,337,593,543,950,335 if no decimal is use


+/- 7.9228162514264337593543950335 (28 decimal places).
Data Types
6

 Non-numeric Data Types


 Nonnumeric data types are data that cannot be manipulated mathematically
using standard arithmetic operators.
 The non-numeric data comprises text or string data types, the Date data types,
the Boolean data types that store only two values (true or false), Object data
type and Variant data type

Data Type Storage Range of Values


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
Data Types
7

 Suffixes for Literals


 Literals are values that you assign to a data. In some cases, we need to
add a suffix behind a literal so that VB can handle the calculation more
accurately
Suffix Data Type
& Long
! Single
# Double
@ Currency
 Example:
memberName = “Turban, John”
TelNumber = “1800-900-888-777”
LastDay = #31-Dec-00#
ExpTime = #12:00 am#
Data Types
8

 User-Defined Types
 createyour own data type.
 a new data type by combining the built-in data types

 Format to define a data type is


Type variable_name
Statements
End Type
Data Types
9

 User-Defined Types
 Example:
Dim group As Student
group.StuName = "James"
Type Student
group.StuID = "1007"
StuName As String
group.StuYear = "Final Year"
StuID As String
group.StuFee = "$20,000"
StuFee As Currency
Cells(2, 2) = group.StuName
StuYear As String
Cells(3, 2) = group.StuID
End Type
Cells(4, 2) = group.StuYear
Cells(5, 2) = group.StuFee
Variables & Data Types
PRACTICAL LEARNING
10

 Dim variableName as DataType

 Example
 Dim password As String
 Dim yourName As String
 Dim firstnum As Integer
 Dim secondnum As Integer
 Dim total As Integer
 Dim BirthDay As Date

 separating each variable with a comma, as follows:


 Dim password As String, yourName As String, firstnum As Integer
Variables & Data Types
PRACTICAL LEARNING
11

 Example: we declared three types of variables, namely the string, date


and currency.

Private Sub CommandButton1_Click()


Dim YourName As String
Dim BirthDay As Date
Dim Income As Currency
YourName = "Alex"
BirthDay = "1 April 1980"
Income = 1000
Range("A1") = YourName
Range("A2") = BirthDay
Range("A3") = Income
End Sub
Variables & Data Types
PRACTICAL LEARNING
12

 Using Byte Variables

Sub Variables()
Dim Shirts As Byte
Dim Pants As Byte
Dim OtherItems As Byte
Dim TotalItems As Byte

Shirts = 6
Pants = 4
OtherItems = 2
TotalItems = Shirts + Pants + OtherItems
ActiveCell.FormulaR1C1 = TotalItems
End Sub
Variables & Data Types
PRACTICAL LEARNING
13

 Using Decimal Variables

Sub Variables()
Dim Side As Double
Dim Perimeter As Double Side = 32.75

Perimeter = Side * 4

ActiveCell.FormulaR1C1 = Perimeter
End Sub
Variables & Data Types
PRACTICAL LEARNING
14

 Using a String
Sub Variables()
Dim CustomerName As String

CustomerName = "Paul Bertrand Yamaguchi"

ActiveCell.FormulaR1C1 = CustomerName
End Sub
Variables & Data Types
PRACTICAL LEARNING
15

 Using Currency Values

Sub Variables()
Dim NumberOfShirts As Byte
Dim PriceOneShirt As Currency
Dim TotalPriceShirts As Currency

NumberOfShirts = 5
PriceOneShirt = 1.25
TotalPriceShirts = NumberOfShirts * PriceOneShirt

ActiveCell.FormulaR1C1 = TotalPriceShirts
End Sub
Variables & Data Types
PRACTICAL LEARNING
16

 Using a Date

Sub Variables()
Dim DepositDate As Date
DepositDate = #2/5/2008#

ActiveCell.FormulaR1C1 = DepositDate
End Sub
Use of Option Explicit
17

 The use of Option Explicit


 help us to track errors in the usage of variable names within
a program code
 For example, if we commit a typo, VBE will pop up an error
message “Variable not defined”.
 It is a good practice to use Option Explicit because it will
prevent us from using incorrect variable names due to
typing errors, especially when the program gets larger.

 With the usage of Option Explicit, it will save us time in


debugging our programs.
Use of Option Explicit
PRACTICAL LEARNING
18

 Example
Option Explicit
Private Sub CommandButton1_Click()
Dim YourName As String, password As
String
YourName = "John"
password = 12345
Cells(1, 2) = YourNam
Cells(1, 3) = password
End Sub
Assigning Values to the Variables
19

 Value Assignment
 Use the assignment operator (=) followed by the value
you need to store
 The general format of an assignment is
Variable=Expression
 Example
Dim Value
Value = 100
Arithmetic Operations
20

Operator Mathematical function Example

^ Exponential 2^4=16
* Multiplication 4*3=12
/ Division 12/4=3
Mod Modulus (return the remainder 15 Mod 4=3
from an
integer division)
\ Integer Division (discards the 19\4=4
decimal places)
+ or & String concatenation "Visual"&"Basic"="Visual
Basic"
Arithmetic Operations
PRACTICAL LEARNING
21

Option Explicit
Private Sub CommandButton1_Click ()
Dim number1, number2, number3 as Single
Dim total, average as Double
number1=Cells (1, 1).Value
number2=Cells (2, 1).Value
number3= Cells (3, 1).Value
Total=number1+number2+number3
Average=Total/3
Cells (5, 1) =Total
Cells (6, 1) =Average
End Sub
Arithmetic Operations
PRACTICAL LEARNING
22

Option Explicit
Private Sub CommandButton1_Click()
Dim secondName As String, yourName As String
firstName = Cells(1,1).Value
secondName = Cells(2,1).Value
yourName = firstName + " " + secondName
Cells(3,1) = yourName
End Sub
23 Using Message box and Input box
Excel VBA
MsgBox ( ) Function
24

 MsgBox function is to produce a pop-up message box and


prompt the user to click on a command button before he or
she can continue.

 The format for a message box is as follows:


 message=MsgBox(Prompt, Style Value, Title)

 Prompt, will display the message in the message box


 Style Value determines what type of command button will
appear in the message box
 Title argument will display the title of the message board
 Message is a variable that holds values that are returned by the
MsgBox ( ) function.
MsgBox ( ) Function
25

 Style Values and Command Buttons


Style Value Named Constant Button Displayed
0 vbOkOnly Ok button
1 vbOkCancel Ok and Cancel buttons
2 vbAbortRetryIgnore Abort, Retry and Ignore buttons.
3 vbYesNoCancel Yes, No and Cancel buttons
4 vbYesNo Yes and No buttons
5 vbRetryCancel Retry and Cancel buttons

 Example:
yourMsg=MsgBox( "Click OK to Proceed", 1, "Startup Menu")

yourMsg=Msg("Click OK to Proceed". vbOkCancel,"Startup Menu")


MsgBox ( ) Function
26

 Returned Values and Command Buttons


Value Named Constant Button Clicked

1 vbOk Ok button
2 vbCancel Cancel button
3 vbAbort Abort button
4 vbRetry Retry button
5 vbIgnore Ignore button
6 vbYes Yes button
7 vbNo No button
MsgBox ( ) Function
PRACTICAL LEARNING
27

Private Sub CommandButton1_Click()


Dim YourMsg As String
Cells(1, 2) = "Your first VBA program"
YourMsg = Cells(1, 2)
MsgBox YourMsg
End Sub
----------------------------------------------------
Private Sub CommandButton1_Click()
Dim YourMsg As String
Cells(1, 2) = "Your first VBA program"
YourMsg = Cells(1, 2)
MsgBox YourMsg, vbYesNoCancel
End Sub
InputBox( ) Function
28

 InputBox( ) is a function that displays an input box where the user


can enter a value or a message in the form of text.
 The format is:
 myMessage=InputBox(Prompt, Title, default_text,
x-position, y-position)

 myMessage is a variant data type but typically it is declared as a


string, which accepts the message input by the users
 Prompt - The message displayed in the inputbox.
 Title - The title of the Input Box.
 default-text - The default text that appears in the input field where
users can use it as his intended input or he may change it to another
message.
 x-position and y-position - the position or the coordinates of the input
box.
InputBox ( ) Function
PRACTICAL LEARNING
29

Private Sub CommandButton1_Click()


Dim userMsg As String
userMsg = InputBox("What is your message?",
"Message Entry Form", "Enter
your messge here", 500, 700)
Cells(1,1).Value=userMsg
End Sub
30 Exercises
Variables, Arithmetic Operators
Simple Addition Example
PRACTICAL LEARNING
31

 Excel Macro

Sub ADD_Macro()
Dim X As Integer
Dim Y As Integer

X = Sheet2.Range("A1")
Y = Sheet2.Range("A2")

Sheet2.Range("B1") = X + Y

End Sub
Simple Addition Example
PRACTICAL LEARNING
32

 Developer Form Control

Private Sub RESULT_Click()


Dim X As Integer
Dim Y As Integer

X = Val(NUM1.Text)
Y = Val(NUM2.Text)

SUM.Text = Str(X + Y)

End Sub
Exercises
33

 Create a Calculator Program which


operates addition, subtraction ,
multiplication and division between 2
numbers.
 Excel Macro (Sheet1)
 Developer Form Control
 Filename:
 02_CALCULATOR (save as Excel Macro Enable)

 Create a Weight and Height Converter


Program. kg->lbs, lbs->kg, ft->cm, cm->ft
 Excel Macro (Sheet1)
 Developer Form Control
 Filename:
 03_CONVERTER (save as Excel Macro Enable)
Exercises
34

 Revised the Calculator Program which get range of


10 values at COL A & COL B. Do operation of sum,
difference, product, quotient, average & modulus.
 Excel Macro (Sheet1)
 Developer Control
 Filename:
 04_CalcRange (save as Excel Macro Enable)

 Create a program that will get 3 set of strings


(firstname, middlename & surname) from 5 users
and display format the following format:
 Surname, Firstname Middlename
 Firstname Middlename Surname

 Excel Macro (Sheet1)


 Developer Control
 Filename:
 05_String (save as Excel Macro Enable)
References
35

 Excel® VBA Programming For Dummies®, 3rd ed.,


by John Walkenbach, © 2010
 Excel VBA Made Easy by Liew Voon Kiong © 2009
 http://www.vbtutor.net/VBA/vba_tutorial.html
 http://www.functionx.com/vbaexcel/index.htm

You might also like