Private Sub workbook_open()
Select the range of cells
Dim r1, r2, r3, r4, r5, multirange
Set r1 = Sheets("SE_SQ").Range("Ad1:ak50")
Set r2 = Sheets("Main").Range("Ad1:ak50")
Set r3 = Sheets("Feeler").Range("Ad1:ak50")
Set r4 = Sheets("Egg Crates").Range("Ad1:ak50")
Set r5 = Sheets("other").Range("Ad1:ak50")
Set multirange = Union(r1, r2, r3, r4, r5)
这最后一个设定范围给出了一个运行时错误1004.这个陈述有什么问题?
答案 0 :(得分:0)
Excel的Union()
不适用于不同工作表的范围。将所有范围复制到一个工作表中或考虑使用其他VBA容器(如集合,数组或字典)。下面通过所有这些容器传递范围值,并在每个容器中迭代打印值:
Public Sub RangeTest()
Dim r1, r2, r3, r4, r5
Dim d1 As New Collection, d2(1 To 250) As Variant, d3 As Object
Dim i As Variant, n As Variant, num As Integer
Set r1 = Sheets("SE_SQ").Range("Ad1:ak50")
Set r2 = Sheets("Main").Range("Ad1:ak50")
Set r3 = Sheets("Feeler").Range("Ad1:ak50")
Set r4 = Sheets("Egg Crates").Range("Ad1:ak50")
Set r5 = Sheets("other").Range("Ad1:ak50")
' COLLECTION '
For Each i In Array(r1, r2, r3, r4, r5)
For Each n In i
d1.Add n
Next n
Next i
For Each i In d1: Debug.Print i: Next i
' ARRAY '
num = 1
For Each i In Array(r1, r2, r3, r4, r5)
For Each n In i
d2(num) = n
num = num + 1
Next n
Next i
For Each i In d2: Debug.Print i: Next i
' DICTIONARY '
Dim key As Variant, val As Variant
Set d3 = CreateObject("Scripting.Dictionary")
num = 1
For Each i In Array(r1, r2, r3, r4, r5)
For Each n In i
key = num: val = n: d3.Add key, val
num = num + 1
Next n
Next i
For Each i In d3: Debug.Print d3(i): Next i
End Sub