不正常的 Excel VBA 函数参数处理现象
source link: https://zhiqiang.org/coding/unusual-byref-behavior-excel-vba.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
不正常的 Excel VBA 函数参数处理现象
无意中发现一个 Excel VBA 对待参数的一个"不正常"现象。这种处理方式可能无意中导致程序结果错误,而且你很难发现你的错误所在:
Sub twotimes(t As Double) t = 2 * t End Sub Sub test() Dim t As Double t = 123 twotimes t MsgBox t ' 输出 246 t = 123 twotimes (t) MsgBox t ' 输出 123 t = 123 Call twotimes(t) MsgBox t ' 输出 246 End Sub
test 函数对于 twotimes 有三种调用方法,分别为 twotimes t , twotimes (t)和 call twotimes(t)。它们是一样的吗?
运行 test 之后,第一种方法和第三种方法都输出了 246。这个没有问题,因为 VBA 的参数默认传引用, twotimes 函数会修改 t 的值。但第二种方法输出了 123。我猜测是因为实际调用了 twotimes((t)),从而把(t)传引用进入了 twotimes 的函数体,这个括号在运行时并没有被编译器扔掉,(t)是一个临时变量,和 t 被当作不同的变量。
事实上,空格后面的括号里的变量会被执行,然后返回默认参数。下面是一个更精妙的例子,客官们可以猜测发生什么:
` {style="color:#000020;"} Sub test() Dim myCollection As Collection Dim myObject As Object
myCollection.Add (myObject) myCollection.Add myObject
End Sub `
在函数调用时应该尽量避免第二种写法。
Q. E. D.
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK