我试图尝试一些由 JaredParByRef vs ByVal Clarification回答的东西
VB.NET 中的ByVal
意味着提供的值的副本将被发送到函数。对于值类型 (Integer
,Single
等),这将提供值的浅表副本。对于较大的类型,这可能是低效的。对于引用类型,虽然 (String
,类实例) 将引用的副本传递给。
VB.NET 中的ByRef
意味着对原始值的引用将被发送到函数 (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 子程序不需要在参数列表周围使用大括号。但是,如果您传递单个参数并将其括在大括号中,则传递的是表达式。表达式不能通过引用传递。它们被评估,其结果被传递。因此,您必须删除调用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
当然,当函数或 sub 具有多个参数时,问题将立即清楚,因为逗号不能出现在表达式中。
改变这一点:
testingRoutine (trythis)
对此:
testingRoutine trythis
那就试试吧.
另外,看看会发生什么,如果我把它改成这个,函数被用作一个函数(返回的东西)
Sub test1()
Dim trythis As Boolean
Dim testit As Boolean
trythis = False
If (Sheets("Sheet1").Range("A1").Value = 1) Then
testit = 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) As Boolean
Debug.Print "Ran Function"
trythis = True
End Function
我会这样做。
Sub test1()
Dim trythis As Boolean
trythis = False
If (Sheets("TESTING").Range("A1").value = 1) Then
tr = testingRoutine(trythis)
If tr 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"
testingRoutine = True
End Function
因为trythis
不是全局变量,所以在函数中更改它将不会在 sub 中执行任何操作。它只会在函数中将trythis
定义为 True 并保留在该范围内。要使trythis
受函数影响并被子程序读取,您必须将其分配给子程序中的变量。
我不记得我在哪里读到这个,但我知道,如果你在调用子 / 函数时将 bracets()添加到参数中,这是一个特定的(不是错误)方式,微软暗示解决 byref 调用(到 byval)。
例如:假设你调用一个只有 byref 和 2 个参数的子:
call Sub1 (a),(b)
是强制Byval
参数的正确方法,即使它们最初被编码为Byval
本站系公益性非盈利分享网址,本文来自用户投稿,不代表码文网立场,如若转载,请注明出处
评论列表(39条)