【问题标题】:ByRef seems to receive the value and not the reference in VBA 6.0ByRef 似乎收到了价值,而不是 VBA 6.0 中的参考
【发布时间】:2011-06-20 01:51:20
【问题描述】:

我的小示例代码

Function AddNr(ByRef x As Integer) As Integer
    x = x + 2
    AddNr = x
End Function

Sub test()
    Dim ana As Integer
    ana = 1
    AddNr (ana)
    MsgBox ana
End Sub

应该输出 3 但输出 1。更具体地说,ana 变量在调用 AddNr 函数后不会被修改。

我的环境是 Excel 2007 中的 Microsoft Visual Basic 6.5。

【问题讨论】:

    标签: vba pass-by-reference pass-by-value


    【解决方案1】:

    应该是:

     AddNr ana
    

    也就是说,没有括号。

    来自 Microsoft 帮助:

    备注

    您不需要使用通话 调用过程时的关键字。 但是,如果您使用 Call 关键字 调用一个需要 参数,参数列表必须是 括在括号中。如果你省略 Call 关键字,你也必须省略 参数列表周围的括号。 如果您使用任一调用语法调用 任何内在的或用户定义的 函数,函数的返回值 被丢弃。

    【讨论】:

      【解决方案2】:

      Remou 已经搞定了,但我认为括号在函数调用中的作用可以稍微充实一些。向过程调用中的参数添加额外组括号会强制该参数按值传递,而不管被调用的过程是希望通过引用还是按值传递参数。微软关于这个主题的官方帮助页面在这里:How to: Force an Argument to Be Passed by Value (Visual Basic)

      这个概念最容易用一个例子来解释:

      Sub Foo(ByRef Bar)
          Bar = 1
      End Sub
      
      Sub TestFoo()
      Dim Bar
          Bar = 0
          Foo Bar   'The variable Bar is passed ByRef to Foo
          Debug.Print Bar '--> 1
      
          Bar = 0
          Foo (Bar)  'The expression (Bar) is evaluated and 
                     '  the resultant value 0 is passed ByVal to Foo
          Debug.Print Bar '--> 0
      
          Bar = 0
          Call Foo(Bar)  'The variable Bar is passed ByRef to Foo
          Debug.Print Bar '--> 1
      
          Bar = 0
          Call Foo((Bar))  'The expression (Bar) is evaluated and 
                           '  the resultant value 0 is passed ByVal to Foo
          Debug.Print Bar '--> 0
      End Sub
      

      【讨论】:

        猜你喜欢
        • 2019-03-16
        • 2021-10-22
        • 2016-06-05
        • 2017-04-06
        • 2012-06-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多