我正在处理一个宏,该宏将从6个不同的列中获取值并将它们组合成一列,然后使用另外6列中的相应值执行相同的操作。
一个澄清的例子(为了简洁,每个使用3列而不是6列):
|School 1|School 2|School 3|City 1|City 2|City 3|
|a |b |c |1 |2 |3 |
成为值为
的数组array(0,0) = a
array(1,0) = b
array(2,0) = 3
array(0,1) = 1
array(1,1) = 2
array(2,1) = 3
每列有2000行。我目前的代码看起来像这样。
Sub split_other()
Dim collector(11999, 1) As String
Dim counter1 As Integer
counter1 = 0
Dim i As Range
Dim Schools As Range
Set Schools = ActiveWorkbook.Worksheets("Parsing").Range("AB3", "AH2000")
Dim Cities As Range
Set Cities = ActiveWorkbook.Worksheets("Parsing").Range("AJ3", "AP2000")
For Each i In Schools
collector(counter1, 0) = i.Value
counter1 = counter1 + 1
Next
For Each i In Cities
collector(counter1, 1) = i.Value
counter1 = counter1 + 1
Next
End Sub
我遇到的问题是,通过观察Locals视图,我可以看到For Each循环没有填充数组。此外,宏最终会遇到类型不匹配错误。前者是更直接关注的问题。
答案 0 :(得分:1)
只需将值直接分配给数组:
Sub split_other()
Dim collector() As Variant
With ActiveWorkbook.Worksheets("Sheet1")
ReDim collector(1 To .Range("AB3", "AH2000").Cells.Count, 1 To 2) As Variant
Dim counter1 As Integer
counter1 = 1
Dim i As Variant
Dim Schools() As Variant
Schools = .Range("AB3", "AH2000").Value
Dim Cities() As Variant
Cities = .Range("AJ3", "AP2000").Value
For Each i In Schools
collector(counter1, 1) = i
counter1 = counter1 + 1
Next
counter1 = 1
For Each i In Cities
collector(counter1, 2) = i
counter1 = counter1 + 1
Next
.Range("AQ3").Resize(UBound(collector, 1), UBound(collector, 2)).Value = collector
End With
End Sub