我有一个我想要展平的分层数组,以便更容易迭代。 什么是在VBA中展平分层数组的最佳方法?
分层数组的Visual :
s
p
t
d
n
x
展平数组的视觉
s
p
t
d
n
x
已实施分层数组:
Sub test()
Dim s As String
Dim v() As Variant
v = Array("s", Array("p", "t", Array("d", "n")), "x")
MsgBox printHier(v)
End Sub
Function printHier(v, Optional layer As Integer = 0) As String
On Error GoTo ErrorHandler
indent = layer * 4
Do While indent > 0
output = output & " "
indent = indent - 1
Loop
printHier = output & CStr(v)
Exit Function
ErrorHandler:
For Each subv In v
If printHier = vbNullString Then
printHier = printHier(subv, layer + 1)
Else
printHier = printHier & vbNewLine & printHier(subv, layer + 1)
End If
Next subv
End Function
答案 0 :(得分:3)
没有"最好"方式,但这是一种方法:
Sub test()
Dim v() As Variant
Dim arrout()
v = Array("s", Array("p", "t", Array("d", "n", Array("x", "y"))), "x")
ReDim arrout(0 To 0)
Flatten v, arrout
Debug.Print Join(arrout, ",")
End Sub
Sub Flatten(arrIn, arrout)
Dim v, a, ub
For Each v In arrIn
If TypeName(v) Like "*()" Then
Flatten v, arrout
Else
If IsEmpty(arrout(0)) Then
arrout(0) = v
Else
ub = UBound(arrout)
ReDim Preserve arrout(0 To ub + 1)
arrout(ub + 1) = v
End If
End If
Next v
End Sub