VBA 在弹出窗口中显示,不允许我迭代具有用户定义类型的数组。
我写了一些代码,想知道如何解决这个问题。
这是一个小例子,重点关注我想要做的事情。
Option Explicit
Type Info
source As String
destination As String
End Type
Sub specialCopy()
Dim target As Variant
Dim AllTargets() As Info: AllTargets = SetAllTargets()
For Each target In AllTargets
CopyValues (target)
Next
End Sub
Function SetAllTargets() As Info()
Dim A As Info: A = SetInfo("A1", "B1")
Dim B As Info: B = SetInfo("A2", "B2")
Dim AllTargets() As Info
Set AllTargets = Array(A, B)
End Function
Function SetInfo(source As String, target As String) As Info
SetInfo.source = source
SetInfo.destination = destination
End Function
Sub CopyValues(target As Info)
Range(target.source).Select
Selection.Copy
Range(target.destination).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
End Sub
我如何迭代我的AllTargets
大批?
由于我无法编译此文件,因此这里可能存在多个问题。
我不完全确定我设置的方式是否AllTargets
list 是有效的语法。
我重新编写了示例以缩小代码中的问题范围:
Option Explicit
Type Info
source As String
destination As String
End Type
Sub specialCopy()
Dim target As Variant
Dim AllTargets As Collection: Set AllTargets = SetAllTargets()
For Each target In AllTargets
CopyValues (target) '2. unkown if this is possible
Next
End Sub
Function SetAllTargets() As Collection
Dim A As Info: A = SetInfo("A1", "B1")
Dim B As Info: B = SetInfo("A2", "B2")
Set SetAllTargets = New Collection
SetAllTargets.Add (A) '1. problem here when assigning user type
SetAllTargets.Add (B) '1. problem here when assigning user type
End Function
Function SetInfo(source As String, destination As String) As Info
SetInfo.source = source
SetInfo.destination = destination
End Function
Sub CopyValues(target As Info)
Range(target.source).Select
Selection.Copy
Range(target.destination).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
End Sub
代码从数组变为集合 - 尽管如此,其中仍然存在我现在无法解决的问题。
我认为根本原因保持不变:使用用户定义的类型。
我把我认为问题所在的地方标记为评论。