VBA Excel中的魔术括号

Yum*_*hka 6 excel vba excel-vba

我写了一些函数来添加一些折线到Excel工作表.然后我发现了奇怪的括号行为.我声明并定义点数组如下:

Dim points As Variant
Dim sh As Shape

points = Array(Array(10.5, 10.5), Array(20.4, 20.4), Array(5.1, 30.3), Array(10.5, 10.5))

' These both do not work and I get error about wrong type (error 1004) in 2007
' and application defined error 1004 on 2010:

ActiveWorkbook.ActiveSheet.Shapes.AddPolyline points
Set sh = ActiveWorkbook.ActiveSheet.Shapes.AddPolyline(points)

' These work fine:

ActiveWorkbook.ActiveSheet.Shapes.AddPolyline (points)
Set sh = ActiveWorkbook.ActiveSheet.Shapes.AddPolyline((points))
Run Code Online (Sandbox Code Playgroud)

VBA括号的奇怪魔力是什么?

测试了2007年和2010年版本.

GSe*_*erg 6

附加的括号points使得参数被计算为表达式并因此被传递ByVal.

评估数组的行为可以准确地改变数据在Variant包含它的内部的打包方式(例如,当使用变量作为示例传递列数组时,请参阅VBA:删除重复项失败),并且如果被调用的过程不是很宽松它可以接受什么类型的数组(它应该是什么),然后它会引发错误.

在你的情况下,我实际上感到惊讶的是,通过评估(points)甚至可以工作,因为文档提到了Singles 的2D数组是预期的,并且Array(Array(...), Array(...), ...)是与2D数组相对的锯齿状数组.它似乎AddPolyline也是为了应对锯齿状数组而写的,但只有在包含数组的Variant中有一组特定的标志时才能识别它们,这些标志似乎产生了评估(例如,它可能存在或不存在VT_BYREF其标志行程)比较所以它无法识别所支持的传递数组).

我会把它称为bug AddPolyline,我会明确定义并填充2D数组Single以避免它:

Dim points(1 To 4, 1 To 2) As Single
points(1, 1) = 10.5: points(1, 2) = 10.5
points(2, 1) = 20.4: points(2, 2) = 20.4
points(3, 1) = 5.1: points(3, 2) = 30.3
points(4, 1) = 10.5: points(4, 2) = 10.5
Run Code Online (Sandbox Code Playgroud)