Escolar Documentos
Profissional Documentos
Cultura Documentos
Sub math()
Dim num1 As Double, num2 As Double
Dim diff As Double, prod As Double
Sheets("Sheet1").Select
Range("B2").Select: num1 = ActiveCell.Value
Range("B3").Select: num2 = ActiveCell.Value
diff = num1 - num2
prod = num1 * num2
Range("B5").Select: ActiveCell.Value = diff
Range("B6").Select: ActiveCell.Value = prod
End Sub
Create a button to run the macro.
We will now change the math Sub procedure so that obtaining the values from the worksheet and the
subtraction/multiplication will be handled by separate Sub procedures.
Option Explicit
Sub math()
Dim num1 As Double, num2 As Double
Dim diff As Double, prod As Double
Call getvals(num1, num2)
Call calcdp(num1, num2, diff, prod)
MsgBox num1 & " " & num2 & " " & diff & " " & prod
Range("B5").Select: ActiveCell.Value = diff
Range("B6").Select: ActiveCell.Value = prod
End Sub
Sub calcdp(num1, num2, diff, prod)
diff = num1 - num2
prod = num1 * num2
End Sub
Sub getvals(num1, num2)
Sheets("Sheet1").Select
Range("B2").Select: num1 = ActiveCell.Value
Range("B3").Select: num2 = ActiveCell.Value
End Sub
No variables in calcdp or getvals need to be declared because they are all in argument list.
In the argument list, the first arguments are linked, second arguments are linked, etc.
Variable Scope:
By default, variables are locally defined.
Example: [ACT IT OUT IN CLASS]
In this example, we take another look at how arguments are passed to Sub procedures.
Try running this code:
Option Explicit
Sub main()
Dim a As Double, b As Double, x As Double, y As Double
a = 1: b = 2: x = 5: y = 6
MsgBox "Before subby: " & a & " " & b & " " & x & " " & y
Call subby(a, b, x, y)
MsgBox "After subby: " & a & " " & b & " " & x & " " & y
End Sub
Sub subby(n, m, a, b)
Dim x As Double, y As Double
MsgBox "Start of subby: " & a & " " & b & " " & x & " " & y
n = 15: m = 40: a = 100: b = 200: x = 0.1: y = 0.2
MsgBox "End of subby: " & a & " " & b & " " & x & " " & y
End Sub
This example shows that variables have local scope; Variables are affected only by commands within their own
procedure. A variable called x in main( ) is distinct from a variable called x in subby( ). If x is changed in
subby( ), it does not affect the variable x in main( ).
It is possible to extend the scope of a variable to all procedures in a module or to an entire project (see Chapter
8), but it is not recommended and we will not be learning about it in this class.