Vous êtes sur la page 1sur 14

Declaring Variables

Variables are used in coding to hold values, and enable various functions
and calculations. When you create one, you will have to choose from a list
of available data types. The basic syntax for doing this is:
Dim x as _______
Where x is the name of your variable (you can use any name that you
want), and underscore is replaced by the desired data type.

Types:
Boolean: These variables will be able to have values of True or False.
They cannot contain arbitrary numeric or text values.
Date: Holds a date between January 1st, 0100 and December 31st, 9999.
This creates an obvious Y10K issue if youre planning using the same
Excel file for the next 7,985 years.
String: Holds a text string. The size limitation is not an issue. They can
hold 2 billion characters.
Integers: These represent numbers without decimal places. They can
have positive or negative values. These variables take up a limited
amount of data and are subsequently limited to values between 32,768
and -32,768.
Decimal: These variables take up more space and allow for more
accuracy. Because of this they can be slower, too. They can store numbers
that contain approximately 28 number places.
Assigning Values to Variables

If all you want to do is give your variable a fixed value, then you can use
the following syntax:
X=5
Using worksheet cells value:
X = Worksheets(name of worksheet).Cells(2,B).value

Recording a Macro:

Select Record New Macro... under Tools...Macro

In the Background Color Panel, select the Ligth Yellow color box. This action will set the
background of the current cell (A1) in light yellow color.

To stop the macro recording

See the Recorded Syntax and press [Alt] and [F11]


Double click the Module1 folder to see the sub routine (marco).

Now run the Recorded Macro, On any worksheet, select from D3 to E6 and Run the
recorded macro by select Tools...Macro.
Cells D3 to E6 now have light yellow background color

Return to Top of Page

Modules and Procedure:

A module is a container for procedures as shown in our prior examples. A


procedure is a unit of code enclosed either between the Sub and End Sub
statement or between the Function and End Function statements

The following sub procedure (or sub routine) print the current date and time on cell C1:
Sub ShowTime()
Range("C1") = Now()
End Sub
The following function sum up two numbers:
Function sumNo(x, y)
sumNo = x + y
End Function
Procedures in Visual Basic can have either private or public scope.

A procedure with private scope is only accessible to the other procedures in the
same module

Procedure with public scope is accessible to all procedures in in every module in


the workbook in which the procedure is declared, and in all workbooks that
contain a reference to that workbook

By default, a procedure has public scope.


Public Sub ShowTime()
Range("C1") = Now()
End Sub
Private Sub ShowTime()
Range("C1") = Now()
End Sub

Sub procedures:

A sub procedure declaration statement starts with the keyword Sub


Sub Greetings()

MsgBox "Welcome!"

End Sub

Function Procedures

A sub-procedure is a set of vba codes or statements which perform


an action, but does not "return a value".

A Function is also used to perform an action or calculation (which


can also be performed by a sub procedure) but "returns a value",
which is a single value.

Example 1

===================== Function
=====================================
Function partNames() As String

Dim strFirstName As String


Dim strSurName As String
strFirstName = InputBox("Enter first name")
strSurName = InputBox("Enter sur name")
partNames = strFirstName & " " & strSurName
End Function

=========================Sub
Procedure======================
Sub fullName()
ActiveSheet.Range("A1") = partNames
End Sub

Placement of Macros / Sub procedures in appropriate


Modules

Standard Code Modules:

Procedures in standard modules can be called from a procedure in


an outside module just like you call a procedure located in the same
module ie. without specifying the module of the called procedure.

Workbook module:

ThisWorkbook is the name of the module for the workbook and is


used to place workbook events and Application Events

Workbook events are actions associated with the workbook, to


trigger a VBA code or macro. Opening / closing / saving / activating /
deactivating the workbook are examples of workbook events with a
workbook open event and can run a sub-procedure automatically
when a workbook is opened.

Sheet Modules:

A sheet module has the same name as the worksheet's code name
with which it is associated viz. Sheet1, Sheet2

VBA code written in Sheet1/Sheet2 is accessible to only that


particular sheet only.

UserForm Modules:

UserForm events are pre-determined events that occur for a


particular UserForm and its Controls, examples include Initialize,
Activate or Click and these are placed in the user form code module.

general vba codes and procedures can also be placed in a UserForm,


but you will need to include the UserForm module name in the
reference to call them (from outside that UserForm module)

Class Modules:

Class Modules are used to create new objects and you can create
your own custom events in a class.

A Custom Event is defined and declared in a Class Module using the


Event keyword

Calling a Sub Procedure:


Sub CreateCustomer()
Dim strFullName As String

strFullName = "Prasanta Kumar Behera"


End Sub
Sub Exercise()
CreateCustomer or Call CreateCustomer
End Sub

Returning a Value from a Function


Function GetFullName$()
Dim FirstName As String, LastName As String
FirstName = "Prasanta"
LastName = "Behera"
GetFullName = LastName & " " & FirstName
End Function

Calling a Function
Function CallMe() As String
Dim A As String
A = "Hello World"
CallMe = A
End Function
Sub Exercise()
CallMe
End Sub

Arguments
Sub ProcedureName(Argument)
End Sub

If you are creating a function, the syntax would be:


Function ProcedureName(Argument) As DataType
Function Sub

Calling a Procedure with Argument


Private Function GetFullName$(First As String, Last As String)
Dim FName As String
FName = First & Last
GetFullName = FName
End Function
Sub Exercise()
Dim FirstName As String, LastName As String
Dim FullName As String
FirstName = "Prasanta "
LastName = "Behera"
FullName = GetFullName(FirstName, LastName)
Msgbox = FullName
End Sub

Passing Arguments by Value

By default we always have pass by value

Private Sub ShowResult(ByVal Result As Double)


Result = 100
End Sub
Public Sub Exercise()
Dim Number As Double
ShowResult Number
Msgbox = Number
End Sub

Passing Arguments by Reference:


Private Sub ShowResult(ByRef Result As Double)
Result = 100
End Sub
Public Sub Exercise()
Dim Number As Double
ShowResult Number
Msgbox = Number
End Sub

String Functions:
Len Function

Syntax: Len(string | varname)


=LEN("Excel")
Result: 5

=LEN("123")
Result: 3
LCase Function
Syntax: LCase ( string )
Example:
Print Lcase("Good Morning")
'Output --> good morning
UCase Function
Syntax: UCase(string)
Example:
Print Ucase("Good Morning")
'Output --> GOOD MORNING
Left Function
Syntax: Left(string, length)
Example:
Print Left("Good Morning",4)
'Output --> Good
Right Function

Syntax: Right(string, length)


Example:
Print Right("Good Morning",7)
'Output --> Morning
Mid Function:
Syntax: Mid(string, start[, length])
Example:
Print Mid("Good Morning",6)
'Output --> Morning
Replace Function
Syntax: Replace(expression, find, replacewith[, start[, count[, compare]]])
Example:
Print Replace("Good Morning","Morning","Night")
'Output --> Good Night
Space Function
Syntax: Space(number)
Example:
Space(7)
'Output --> "
"

Looping Concept:
For Next:
Syntax:
For counter = start To end [Step step]
[statements]
[Exit For]
[statements]
Next
Example1:
Dim i As Integer
For i = 1 To 5
Cells(i, 1).Value = 100

Next i
Result in excel:

Example2:
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 in excel:

For Each loop:


Syntax:
For Each element In group
[statements]
[Exit For]
[statements]
Next [element]
Sub For_Each_Collection()
Dim rRange As Range

Dim rCell As Range

Set rRange = Range("A1", Range("A65536").End(xlUp))

For Each rCell In rRange


MsgBox rCell.Value
Next rCell
End Sub

Do While Loop:
Syntax:
Do [{While | Until} condition]
[statements]
[Exit Do]
[statements]
Loop
OR
Do
[statements]
[Exit Do]
[statements]
Loop [{While | Until} condition]
Example:

Dim i As Integer
i=1
Do While i < 6
Cells(i, 1).Value = 20
i=i+1
Loop
Result in excel:

If...Then...Else Statement
Syntax:

If condition Then statements [Else elsestatements ]


OR
If condition Then
[statements]
[ElseIf condition-n Then
[elseifstatements]] . . .
[Else
[elsestatements]]
End If
Example:

Dim score As Integer, result As String


score = Range("A1").Value
If score >= 70 Then result = "pass"
Range("B1").Value = result
Result in excel:

Dim score As Integer, result As String


score = Range("A1").Value
If score >= 60 Then
result = "pass"
Else
result = "fail"
End If
Range("B1").Value = result

Select Case statement:

Syntax:

Select Case testexpression


[Case expressionlist-n
[statements-n]] . . .
[Case Else expressionlist-n
[elsestatements-n]]
End Select
Example:

score = Range("A1").Value

Select Case score


Case Is >= 80
result = "very good"
Case Is >= 70
result = "good"
Case Is >= 60
result = "sufficient"
Case Else
result = "very bad"
End Select
Range("B1").Value = result
Result in Excel:

While...Wend statement:

Syntax:
While condition
Version [statements]
Wend
Example:

Counter =1
While Counter < 4
Total =Inputbox("Please enter the total marks in numbers")
If Total < 50 Then
MsgBox "Fail"
ElseIf Total >=50 and Total <=60 then
Msgbox "Second Class"
ElseIf Total >60 and Total <80 then

Msgbox "First Class"


Else
Msgbox "Invalid Marks"
End If
Counter=counter + 1
Wend

Goto statement:
On Error GoTo Oops
'[more code goes here]
Exit Sub
Oops:
MsgBox "An error occurred"

Vous aimerez peut-être aussi