Vba Programming Basics

You may have situations where you want to pass parameters to subroutines. A parameter is essentially a variable that receives an argument from the statement that you use to call the subroutine. Just like standard variables, you want to specify the data type for the subroutine parameters to avoid converting them into variants.

In the example, the Call statement calls the AddValues subroutine and passes in the values contained in the Valuei and Value2 variables. You can call a subroutine that has parameters from the Macro dialog box. Other procedures typically call subroutines with arguments.


Sub AddValues (Vali As Integer, Val2 As Integer) Dim Total As Integer Total = Vali + Val2 MsgBox (Total) End Sub

Because you cannot call the subroutine as a macro from Excel, you must create a separate subroutine that calls the AddValues subroutine. Within this subroutine you need to specify the values for the Valuei and Value2 parameters that pass to the AddValues subroutine.


Sub TotalValues

Dim Valuei As Integer Dim Value2 As Integer Valuei = 5 Value2 = 7

Call AddValues (Valuei, Value2) End Sub m l-lsl»

□ P" [O]

H] 5heet2 (5heet2)

-ÉQ Sheet3 (Sheet3)

LQ ThisWorkbook

EHSl Modules


Ä Module2

-«ÍJ ModuleU tfí5 Module4 Modules L^ Modules

Module6 Module -1

Alphabetic | Categorized |


Module6 Module -1

Alphabetic | Categorized |


jrJ J Calculate JExpense

Sub Calculate_Expenses()

■ The Visual Basic Editor inserts the End Sub command when you press Enter.

_Q Type the Macro code.

Q Switch to Excel and open the Macro dialog.

0 0

Post a comment