Option Explicit
Sub CalcCost()
'declaration of variables
Dim slsPrice As Currency
Dim slsTax As Single
Dim Cost As Currency
Dim strMsg As String
slsPrice = 39
slsTax = 0.085
Range("A1").Formula = "The cost of calculator"
Range("A4").Formula = "Price"
Range("B4").Formula = slsPrice
Range("A5").Formula = "slsTax"
Range("A6").Formula = "Cost"
Range("B5").Formula = Format((slsPrice * slsTax), "0.00")
Cost = Format(slsPrice + (slsPrice * slsTax), "0.00")
With Range("B6").Formula = Cost
strMsg = "The calculator total is " & "$" & Cost & "."
Range("A8").Formula = strMsg
End Sub
Option Explicit Explanation:
VB使用Option Explicit语句自动提醒你正式地声明你的变量,这个语句必须放在每个模块的最上面。如果你试图运行一个含有未定义的变量的过程时,Option Explicit语句会让VB产生一个错误信息。
技巧:Option Explicit更多信息
Option Explicit强迫正式(显式)声明模块里的所有变量。使用它的一个重大优点是,输入错误会在编译时(VB试图将源代码翻译为可执行代码)被检测到。Option Explicit语句必须在模块里的任何过程之前出现。
不同的变量在VBA过程里有不同的影响范围:
Scope(范围)这个术语定义某个特定的变量在同一个过程,其它过程,或者其它VBA工程里的可用性。变量在VBA里可以是下面三种级别的范围:
过程级别范围:
模块级别范围:
Option Explicit
Dim slsTax As Single
Sub CalcCost( )
<放置过程指令>
End Sub
this slaTax is the module variable
工程级别范围:
模块级别的变量用关键字Public(而不是Dim)声明时,拥有工程级别范围。这意味着它们可以在VBA任何模块里使用。当你想要在一个打开的VBA工程的所有过程里使用某个变量时,必须用Public关键字来声明它,例如:
Option Explicit
Public slsTax As Single
Sub CalcCost( )
<过程代码>
End Sub
注意,变量slsTax在模块上面以Public关键字声明的,它将会在该VBA工程里的任何过程里都可用。
参考文献:https://www.w3cschool.cn/excelvba/excelvba-variable3.html