Constants are declared with the Const keyword. Constants are valuable when you want to assign a value to a variable and have it remain fixed throughout the execution of the code. The syntax for Constants is as follows:
Public | Private Const name [As type] = Expression
A variable or constant with Public scope is available to all procedures in all modules in a project.
A variable or constant with Private scope is only available to procedures in the module that defines it, but not to procedures in other modules.
Examples
Define the mathematical constant pi.
Public Const pi As Double = 3.14159
Control structures
In VBA, control structures are used to determine what should happen, when it should happen, and under what circumstances it should happen. The three most common control structures are branching statements, looping statements, and jumping statements.
-
Branching statements perform a test, and then execute some lines of code but not others.
-
Looping statements execute a portion of code again and again
-
Jumping Statements pause the execution of the current code, jump to a different block of code, and then return back to the original code.
2.Branching Statements
Branching statements include the familiar If … Then conditional, as well as the Select Case statement. Branching statements test for conditions, and then execute certain blocks of code if the conditions are TRUE, and different blocks of code if they are FALSE.
If/Then
The If …Then conditional is probably the most widely used control structure in programming. The syntax for an If statement is as follows:
If logical_expression Then
‘Code to execute if True
Else
‘Code to execute if False
End If
It is entirely possible to nest If statements, but be careful of doing this too many times as the code can become unmanageable very fast. To nest If statements, use a skeleton like the following:
If condition_1 Then
‘Second If Statement
If condition_2 Then
‘Code if True
Else
‘Code if False
End If
Else
‘Code if condition_1 is False
End If
If you want to have multiple tests in a single If statement, you can use ElseIf. ElseIf will enable you test a condition multiple times. Use the following skeleton for an ElseIf statement:
If strBreakfast = “Sausage” Then
‘Code if True
ElseIf strBreakfast = “Donuts” Then
‘Code if True
ElseIf strBreakfast = “Green Eggs and Ham” Then
‘Code if True
Else
‘Code if none of the above are True
End If
Select Case
Select Case is used when you need to make a choice among several different answers. The following example carries out one of five actions depending on what is contained in the variable varCurrentMood. There can be multiple lines of code for each Case.
Select Case varCurrentMood
Case "Sad"
'code for Buy Kleenex and Sob
Case "Mad"
'code for Punch the pillow
Case "Happy"
'code for Smile
Case "Homesick"
'code for Write a letter
Case "Irritated"
'code Smirk
Case Else
'The catch-all phrase for anything that doesn't fit the above.
'None of the above? Then you must be bored. Go out and play.
End Select
3.Looping Statements
Looping statements perform the same action over and over again. There are two main looping structures, For …Next, For Each …Next, and Do …While.
For … Next
Typically the For …Next statement is used when the number of required loops is known, or is stored in a variable. Here is the syntax:
For varCounter = X to Y
‘Code to execute here
Next
varCounter is a variable that the script uses to keep track of the current count. You could name it whatever you want. X and Y can be either numbers, or can be variable names that store numbers. X signifies the starting number to set the counter to, and Y is the end number of loops to perform.
Dim DateStart As Date
Dim DateEnd As Date
Dim NumberOfDays As Integer
Dim varCounter As Integer
DateStart = #7/1/2002#
DateEnd = #7/15/2002#
NumberOfDays = DateEnd - DateStart
For varCounter = 0 To NumberOfDays
'Code to execute here
Next
For Each … Next
The For Each …Next statement is used for looping through items that are in an array or a collection. The syntax is as follows:
For Each Item In varVariable
‘Code to execute here
Next
varVariable can either be the name of an array, or a collection of objects.
Do … While
The Do …While statement is used when you are not sure of the number of loops to perform. On each loop a test is performed, and as long as the condition is met the loop will continue to occur. The syntax is as follows:
Do While varVariable1 < varVariable2
‘Code to execute here
varVariable1 = varVariable1 + 1
Loop
Typically, the value of varVariable1 will change within the loop. In the example it is incremented by 1 each time through the loop. At some point it will become bigger than the value in varVariable2 and the loop will end.
4.Jumping Statements
Jumping Statements are useful when you need reusable chunks of code that need to be called at specific moments. These are essentially mini-programs that force the main program to jump from the main body of code, run through the commands of the mini-program, and then return to the main body of code. There are two types of jumping statements:
-
Sub procedures – Used to carry out actions. A sub procedure does not return values.
-
Functions – Used to carry out actions and to return an answer to the main body of code.
5.Procedures
Sub procedures are used to execute a bit of code, and then return to the main body of the code. The syntax is as follows:
Sub nameofsub()
‘Code to Execute Goes Here
End Sub
You can then execute a sub procedure by calling it using the Call command:
Call nameofsub
6.Functions
Functions are used to execute a bit of code and to return a value back to the main code. The syntax is as follows:
Function NameOfFunction(Parameter) As Integer
'Code to Execute Goes Here
'Assign a value to the function before it ends
'This will be the value that the function returns
NameOfFunction = 10
End Function
Functions can take parameters, meaning they can accepts values from the main body of code and use them during the execution of the function. Inside the parenthesis () you can place the name of a variable that you want to pass to the function. For example, to create a function to calculate the next time to change the oil of a car (current mileage + 3000 miles), you can pass a variable that stores the current mileage into the function, as in the following code:
Dim dCurrentMileage as Double
dCurrentMileage = 145000
Function FindNextOilChange(dCurrentMileage) as Double
When functions are finished performing their calculations, they return the result as a value of a new variable, which is the name of the function. When you create a function and give it a name, that name becomes a variable that will store the resulting value of the function’s calculations. It is not necessary to Dim this variable, it is available for use automatically. So, the code above becomes complete when we assign the value to the function name:
Function FindNextOilChange(dCurrentMileage) as Double
FindNextOilChange = dCurrentMileage + 3000
End Function
It is common to create a new variable, and make the variable equal to the function. This invokes the function and stores the function’s value as a global variable.
Sub CalculateNewMileage()
Dim dCurrentMileage As Double
Dim dNewMileage As Double
dCurrentMileage = 145000
dNewMileage = FindNextOilChange(dCurrentMileage)
MsgBox “The mileage for your next oil change is” & “ “ & dNewMileage
End Sub
Share with your friends: |