我最近开始在Excel中使用嵌套数组。我在使用它们时遇到了一些问题。
我通常用来快速写出数组的方法不再适用。失败的原因似乎是因为我试图找到嵌套数组的维度(参见下面的代码)。我知道我可以使用嵌套的for循环写出数组,但是有更好/更快的方法吗?
Sub print_arr()
Dim test_arr(1 to 10) as variant
for i = 1 to 10
test_arr(i) = Array(1,2,3,4)
next I
'sample Locals readout: test_arr(1)(0) = 1, test_arr(1)(1) = 2, test_arr(1)(2) = 3, test_arr(1)(3) = 4,
Dim Desination as Range
Set Destination = Range("A1")
'normally I would do something like
Destination.Resize(UBound(test_arr, 1), UBound(test_arr, 2)).Value = test_arr
'but this doesn't work for a nested array
'there is an issue with the ubound(test_arr,2)
'so what's the best way to write out nested array to Destination?
End Sub
我希望在运行上述代码后看到的内容如下:
A | B | C | D |
------------------
1: 1 | 2 | 3 | 4 |
2: 1 | 2 | 3 | 4 |
3: 1 | 2 | 3 | 4 |
4: 1 | 2 | 3 | 4 |
5: 1 | 2 | 3 | 4 |
6: 1 | 2 | 3 | 4 |
7: 1 | 2 | 3 | 4 |
8: 1 | 2 | 3 | 4 |
9: 1 | 2 | 3 | 4 |
10: 1 | 2 | 3 | 4 |
另一个相关的问题是:检查test_arr(i)中的值是否是嵌套数组的最佳方法是什么?如果有嵌套数组,则Ubound(test_arr(i))工作并给出预期值3.如果test_arr(i)不是嵌套数组或为空,则ubound(test_arr(i))生成“类型不匹配“错误。