我不喜欢未初始化的 VBA 数组,因为每次使用之前都需要检查数组是否已初始化UBound()或For Each避免异常,并且没有本机 VBA 函数来检查它。这就是为什么我初始化数组,至少用a = Array(). 这在大多数情况下消除了额外检查的需要,因此一维数组没有问题。
出于同样的原因,我尝试创建一个空的二维数组。不可能简单地做ReDim a(0 To -1, 0 To 0),转置一维空数组或类似的东西。我偶然遇到的唯一方法是使用MSForms.ComboBox,将空数组分配给.List属性并将其读回。这是在 Excel 和 Word 中工作的示例,您需要插入UserForm到 VBA 项目中,放置ComboBox在其上,并添加以下代码:
Private Sub ComboBox1_Change()
Dim a()
ComboBox1.List = Array()
a = ComboBox1.List
Debug.Print "1st dimension upper bound = " & UBound(a, 1)
Debug.Print "2nd dimension upper bound = " & UBound(a, 2)
End Sub
Run Code Online (Sandbox Code Playgroud)
组合更改后的输出为:
1st dimension upper bound = -1
2nd …Run Code Online (Sandbox Code Playgroud)