Example #1

Look at the VBA codesVBA CodesVBA code refers to a set of instructions written by the user in the Visual Basic Applications programming language on a Visual Basic Editor (VBE) to perform a specific task.read more below.

Code:

Sub Macro1()

Dim k As Integer

k = 50

Macro2 k

MsgBox k

End Sub

The above two macro procedures have a common variable, “k,” across procedures. Let me explain this in detail before we see the result.

In the first Macro, we have assigned the value of 50 to the variable “k.”

Dim k As Integer

k = 50

Next, we have called the second macro procedure from the first Macro.

Macro2 k

#1 – Upon pressing the F8 key first, it will highlight the first line of the Macro1.

At this point, place a cursor on the variable “k.” It should show the value of the variable “k.”

At the moment, the value of “k” is zero.

#2 – Press the F8 key again, and it will jump to the third line.

Even now, the value of “k” is still zero.

#3 – Press the F8 key now. See the value of the k.

Since the “k” value sets to 50 and the code executes, the value shows as 50.

#4 – The highlighted line is “Macro2 k,” i.e., pressing the F8 key will jump to the second procedure, Macro2.

#5 – Even now, the value of variable “k” in this procedure also shows as 50. But inside this macro, we are resetting the value of the variable “k” as k = k + 5, i.e., 55. So, now press the F8 key two more times.

As you can see above, the “k” value is 55 now.

#6 – Press the F8 key. It will jump back to the Macro1 procedure.

When the macro jumps back to the original procedure Macro1, our variable “k” value is no longer 55 but rather the original value in this procedure, i.e., 50.

When you press the F8 key, we can see only 50 in the message box in VBAMessage Box In VBAVBA MsgBox function is an output function which displays the generalized message provided by the developer. This statement has no arguments and the personalized messages in this function are written under the double quotes while for the values the variable reference is provided.read more.

Example #2

Now, take a look at the below two macros.

Sub P1()

Dim k As Integer: k = 10

Call P2(k)

MsgBox k

End Sub

This macro carries the value of variable “k” as ten from macro “P1” to macro “P2.” So, this macro will reset the value to 15, but the moment it comes back to finish the macro to the first macro, “P1,” the value of “k” back to 10, not 15.

Things to Remember