我在VBA脚本中有一系列变量(每个变量都声明为一个范围),如下所示:
r1 = range
r2 = range
...
r100 = range
理想情况下,我想使用for循环连续选择,复制和粘贴(转置)每个范围。我正在通过反复试验来编写代码,而且我对VBA很熟悉。目前我正在使用如下循环:
For i = 0 To 99 Step 1
Dim Num As Integer
Num = i + 1
Num = CStr(Num)
Dim R As Range
R = "r" & Num
R.Select
Selection.Copy
Range("TARGET RANGE").Select
Selection.PasteSpecial Paste:=xlPasteAll, Operation:=xlNone, SkipBlanks:= _
False, Transpose:=True
Next i
任何人都可以帮我调试这个循环和/或找到实现这个目标的最佳方法吗?
答案 0 :(得分:1)
您需要Set
一个Range object。
Dim Num As Integer, R As Range
For i = 0 To 99 Step 1
Num = i + 1
SET R = RANGE("r" & Num)
R.Copy Destination:=Range("TARGET RANGE")
Next i
您打算完成的目标尚不完全清楚,但上述内容应该符合预期。
答案 1 :(得分:0)
您可以使用For Each ... In
循环。
Dim Bag As New Collection
Dim Target As Range
Dim r As Range
Bag.Add [A1:A50]
Bag.Add [C3:F100]
Bag.Add [Sheet2!H1:L1]
Bag.Add ['[Another file.xlsx]Sheet1'!A1:B100]
Set Target = [Output!A1]
For Each r In Bag
' Size target to be the same dimensions as r transposed
Set Target = Target.Resize(r.Columns.Count, r.Rows.Count)
' transpose and copy values
Target.Value = Application.Transpose(r.Value)
' shift target down to next empty space
Set Target = Target.Offset(Target.Rows.Count)
Next