ByVal和ByRef VBA

马尔德雷德

我试图尝试由JaredPar ByRef与ByVal Clarification回答的问题

ByVal在VB.NET中,意味着将提供的值的副本发送到该函数。对于值类型(IntegerSingle等),这将提供值的浅表副本。对于较大的类型,这可能效率很低。但是String对于引用类型(类实例),将传递引用的副本。由于副本是通过=变量突变传递给参数的,因此调用函数将看不到它。

ByRef在VB.NET中,意味着对原始值的引用将发送到函数(1)。就像原始值直接在函数中使用一样。类似的操作=会影响原始值,并在调用函数中立即可见。

我已经试过用下面的代码来测试它,我似乎无法得到它的工作使用ByRef的单元格的值更改为0,如果它是1

这是我正在测试的以下代码,我在做什么错?的价值Range("A1")仍然是1

Sub test1()

    Dim trythis As Boolean

    trythis = False

    If (Sheets("TESTING").Range("A1").value = 1) Then
        testingRoutine (trythis)
        If (trythis) Then
            Debug.Print "Value changed to 0"
            Sheets("TESTING").Range("A1").value = 0
        End If
    End If

End Sub

Private Function testingRoutine(ByRef trythis As Boolean)

    Debug.Print "Ran Function"
    trythis = True

End Function
保罗·奥吉维

VB子例程不需要在参数列表中使用大括号。但是,如果传递一个参数并将其括在括号中,则将传递一个expression表达式不能通过引用传递。因此,您必须删除通话中的花括号testingRoutine (trythis)并编写testingRoutine trythis

注意:如果您在不使用函数返回值的情况下调用函数,则必须将其编写为过程调用(在参数列表的中间没有大括号)。举个例子:

myVal = myFunction (trythis)   ' trythis will be passed by reference
myFunction (trythis)           ' trythis will be seen as an expression
myFunction trythis             ' trythis will be passed by reference

myVal = mySub (trythis)        ' invalid: mySub is not a function
mySub (trythis)                ' trythis will be seen as an expression
mySub trythis                  ' trythis will be passed by reference

当然,当函数或子函数具有多个参数时,该问题将立即解决,因为逗号不能出现在表达式中。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章