3

我的小示例代码

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。

4

2 回答 2

10

Remou 已经确定了这一点,但我认为括号在函数调用中的作用可以稍微充实一些。在过程调用中为参数添加一组额外的括号会强制该参数按值传递,而不管被调用的过程是通过引用还是按值传递参数。Microsoft 关于此主题的官方帮助页面位于: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
于 2011-02-02T16:28:24.593 回答
6

那应该是:

 AddNr ana

也就是说,没有括号。

从微软帮助:

评论

调用过程时不需要使用 Call 关键字。但是,如果您使用 Call 关键字调用需要参数的过程,argumentlist 必须用括号括起来。如果省略 Call 关键字,则还必须省略argumentlist 周围的括号。如果您使用 Call 语法来调用任何内部或用户定义的函数,则该函数的返回值将被丢弃。

于 2011-02-02T15:54:57.107 回答