我正在尝试在 Excel 中返回一个数组。我一直使用这个网站作为引用:http://www.cpearson.com/excel/returningarraysfromvba.aspx
所以我从这个基本示例脚本开始,它返回一个值矩阵(取自上述站点):
Function Test() As Variant
Dim V() As Variant
Dim N As Long
Dim R As Long
Dim C As Long
ReDim V(1 To 3, 1 To 4)
For R = 1 To 3
For C = 1 To 4
N = N + 1
V(R, C) = N
Next C
Next R
Test = V
End Function
当我使用 ctrl+shift+enter
在 3x4 单元格范围内输入 =Test()
时,我得到了预期的结果:
1 2 3 4
5 6 7 8
9 10 11 12
所以假设现在我想在填充数组时调整数组的大小。我尝试将函数更改为:
Function Test() As Variant
Dim V() As Variant
Dim N As Long
Dim R As Long
Dim C As Long
For R = 1 To 3
For C = 1 To 4
N = N + 1
ReDim Preserve V(1 To R, 1 To C)
V(R, C) = N
Next C
Next R
Test = V
End Function
由于我使用的是 vba IDE,我认为我没有任何方法来诊断为什么上面只返回 #VALUE
。我做错了什么?
最佳答案
来自 MSDN 页面 ReDim statement :
- Resizing with Preserve. If you use Preserve, you can resize only the last dimension of the array. For every other dimension, you must specify the bound of the existing array.
For example, if your array has only one dimension, you can resize that dimension and still preserve all the contents of the array, because you are changing the last and only dimension. However, if your array has two or more dimensions, you can change the size of only the last dimension if you use Preserve.
所以问题是试图重新调整第一个等级(R或第一维度)。您无法使用 Preserve 执行此操作。不过,您可以使用“保留您想要的一切”来重新调整第二等级(C或第二维度)。
ReDim Preserve V(1 To 3, 1 To 1)
For R = 1 To 3
For C = 1 To 4
N = N + 1
ReDim Preserve V(LBound(V, 1) To UBound(V, 1), 1 To C)
V(R, C) = N
Next C
Next R
如果重新调整二维数组的第一列是关键任务,那么首先对其进行转置。
ReDim Preserve V(1 To 1, 1 To 1)
For R = 1 To 3
V = application.Transpose(V)
ReDim Preserve V(LBound(V, 1) To UBound(V, 1), LBound(V, 2) To R)
V = application.Transpose(V)
For C = 1 To 4
N = N + 1
ReDim Preserve V(LBound(V, 1) To UBound(V, 1), LBound(V, 2) To C)
V(R, C) = N
Next C
Next R
我见过在循环中使用它来将更多“行”放入二维数组中,但转置有限制,而且它是额外的处理,尽管是在内存中。
关于vba - 如何在循环中调整数组大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36664051/