ExcelVBA之计算价格及不同变量范围和定义

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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值