我正在构建一个模块,目的是简化多维数组的'Redim'。
主要功能是IncDimension,它采用数组,要重新定义的尺寸以及要添加或删除的位置数。
Public sub main()
Dim v as variant
ReDim a (1 to 3, 1 to 4, 1 to 5)
Call IncDimension(a, 1, 5)
'Before a (1 to 3, 1 to 4, 1 to 5)
'After a (1 to 8, 1 to 4, 1 to 5)
End sub
当维度数在1到9之间时,它可以正常工作,因为我确保每个案例都已实现。但是,假设我可能需要使用超过9维的数组,我的模块是没用的。
有两个地方我必须根据维度数使用Select Case: 当我想'重新''数组
时 Select Case nbDimension
Case 1
ReDim Preserve arr( _
LBound(arr, 1) To UBound(arr, 1) + i)
Case 2
ReDim Preserve arr( _
LBound(arr, 1) To UBound(arr, 1), _
LBound(arr, 2) To UBound(arr, 2) + i)
Case 3
ReDim Preserve arr( _
LBound(arr, 1) To UBound(arr, 1), _
LBound(arr, 2) To UBound(arr, 2), _
LBound(arr, 3) To UBound(arr, 3) + i)
'etc.
当我想在临时数组(tbl)中移动值时
Select Case nbDimension
Case 2
tbl(lstTransferts(1), lstTransferts(2)) = arr(lstIndex(1), lstIndex(2))
Case 3
tbl(lstTransferts(1), lstTransferts(2), lstTransferts(3)) = arr(lstIndex(1), lstIndex(2), lstIndex(3))
'etc.
所以,有没有办法在ReDim Preserve中使用值列表,是否有办法在访问数组时使用索引列表。
答案 0 :(得分:0)
你应该停止这个...这没有意义。首先,为什么需要这样的多维数组?我从未使用超过2个维度,我没有找到任何更大的变体使用。这显然似乎是要求解决一个不适合的问题。你真正的问题是什么?
答案 1 :(得分:0)
我根据维度动态创建了一个模块。
Private Sub creerModuleSelonDimension(ByRef tbl As Variant, ByRef arr As Variant, ByRef lstDimensions As Variant)
Dim vbComp As Object
Dim useReDim As String
Dim dynamicReDim As String
Dim app As Object
Dim i As Integer
'Create the ReDim statement dynamically
dynamicReDim = "ReDim tbl( _" & vbNewLine
For i = LBound(lstDimensions) To UBound(lstDimensions)
dynamicReDim = dynamicReDim + "LBound(arr, lstDimensions(" & i & ")) to UBound(arr, lstDimensions(" & i & ")), _ " & vbNewLine
Next i
dynamicReDim = Left(dynamicReDim, Len(dynamicReDim) - 6) & " _ " & vbNewLine & ")"
'Create the sub
useReDim = "Public Sub useReDim(ByRef tbl as Variant, ByRef arr as Variant, ByRef lstDimensions as variant)" & vbNewLine & dynamicReDim & vbNewLine & "End Sub"
'Create a new module and add the sub in it
Set vbComp = ThisWorkbook.VBProject.VBComponents.Add(1)
vbComp.CodeModule.AddFromString useReDim
'Allow the use of ByRef variables in Application.Run
Set app = Application
'Run useReDim with ByRef variables
i = app.Run(vbComp.Name & ".useReDim", tbl, arr, lstDimensions)
'Delete the new module
ThisWorkbook.VBProject.VBComponents.Remove vbComp
End Sub