VBA/Excel/Access/Word/Language Basics/Variable Declaration — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
|
(нет различий)
|
Текущая версия на 12:46, 26 мая 2010
Содержание
- 1 Declaring Variables
- 2 Forcing Declaration of Variables: Option Explicit
- 3 If you"re going to declare multiple variables on one line, make sure each variable is specifically declared
- 4 To declare a variable in VBA use the Dim (short for Dimension) statement.
- 5 Variable declaration is required with Option Explicit and a module level variable (answer) is declared.
- 6 Variables can also be declared in the declarations section at the top of a module
Declaring Variables
Sub DeclareVariable()
Dim myVar As Integer
End Sub
Forcing Declaration of Variables: Option Explicit
Option Explicit
Sub CalcCost() " revised CalcCost procedure
" declaration of variables
Dim slsPrice As Currency
Dim slsTax As Single
Dim cost As Currency
Dim strMsg As String
slsPrice = 35
slsTax = 0.085
cost = Format(slsPrice + (slsPrice * slsTax), "0.00")
strMsg = "The calculator total is " & "$" & cost & "."
MsgBox strMsg
End Sub
If you"re going to declare multiple variables on one line, make sure each variable is specifically declared
Sub dSub()
Dim intCounter As Integer, intAge As Integer, intWeight As Integer
End Sub
To declare a variable in VBA use the Dim (short for Dimension) statement.
Sub inttype()
Dim myVar As Integer
End Sub
Variable declaration is required with Option Explicit and a module level variable (answer) is declared.
Option Explicit
Dim answer As Integer
Sub Main()
Dim num1 As Integer
Dim num2 As Integer
num1 = Val(InputBox("Please enter the first addend", "First Addend"))
num2 = Val(InputBox("Please enter the second addend", "Second Addend"))
Call AddUserInput(num1, num2)
SendResult
End Sub
Private Sub AddUserInput(num1 As Integer, num2 As Integer)
answer = num1 + num2
End Sub
Private Sub SendResult()
MsgBox ("The answer is " & Str(answer))
End Sub
Variables can also be declared in the declarations section at the top of a module
Option Explicit
Dim Sales
Sub Scope1()
Sales = Sales + 1
MsgBox Sales
End Sub
Sub Scope2()
Sales = Sales + 10
MsgBox Sales
End Sub