我已经使用Set
创建名称为rng1a
格式的范围。然后,我使用循环来遍历i
(整数)值,并希望将最终范围设置为以'rng' & i & "a"
我最初的想法是与Range("rng" & i & "a")
相似,但这会导致错误。
Set rng1a = Range("B2", Range("B2").End(xlDown))
Set rng2a = Range("D2", Range("E2").End(xlDown))
i = 1
Do
("rng" & i & "a").Copy 'this is the problem
Range("A2").End(xlDown).Offset(1,0).PasteSpecial xlPasteValues
i = i + 1
Loop Until i = 3
我不断收到
的错误消息运行时错误'1004':
对象“ _Global”的方法“范围”失败
我的想法是,我需要将范围名称格式化为字符串,以便可以将其识别为范围名称。有办法吗?
答案 0 :(得分:3)
我都没有测试过,但是我认为它们应该可以工作。
请谨慎使用End(xldown)
,好像在第一个单元格下面没有任何内容一样,您将直接进入最后一个单元格。最好从底部开始工作(请参见Damian的答案)。
Sub x1()
'Array
Dim rng(1 To 2) As Range, i As Long
Set rng(1) = Range("B2", Range("B2").End(xlDown))
Set rng(2) = Range("D2", Range("E2").End(xlDown))
For i = 1 To 2
rng(i).Copy
Range("A2").End(xlDown).Offset(1, 0).PasteSpecial xlPasteValues
Next i
End Sub
Sub x2()
'Named ranges
Dim i As Long
Range("B2", Range("B2").End(xlDown)).Name = "rng1a"
Range("D2", Range("E2").End(xlDown)).Name = "rng2a"
For i = 1 To 2
Range("rng" & i & "a").Copy
Range("A2").End(xlDown).Offset(1, 0).PasteSpecial xlPasteValues
Next i
End Sub
答案 1 :(得分:1)
这应该做到:
Option Explicit
Sub Test()
Dim i As Long, LastRow As Long
Dim arrRanges(1 To 2) As Range
With ThisWorkbook.Sheets("NameYourSheet") 'change the sheet name
Set arrRanges(1) = .Range("B2", .Range("B2").End(xlDown))
Set arrRanges(2) = .Range("D2", .Range("E2").End(xlDown))
For i = LBound(arrRanges) To UBound(arrRanges)
LastRow = .Cells(.Rows.Count, 1).End(xlUp).Row + 1
arrRanges(i).Copy .Range("A" & LastRow)
Next i
End With
End Sub
请记住始终声明所有变量,并引用工作簿和工作表。
答案 2 :(得分:0)
您真正想做的(我认为)是将B,C D等列的内容复制到彼此下面的A列中。
Sub CopyStuff
Dim i as integer
dim r as range
for i = 1 to 6
set r = range(cells(1,i),cells(1,i).end(xldown))
r.copy
range("a1").end(xldown).offset(1,0).pastespecial xlpastevalues
next i
End sub
答案 3 :(得分:0)
您可以设置范围数组:
Set rng1a = Range("B2", Range("B2").End(xlDown))
Set rng2a = Range("D2", Range("E2").End(xlDown))
For Each rng in Array(rng1a, rng2a)
rng.Copy
Range("A2").End(xlDown).Offset(1,0).PasteSpecial xlPasteValues
Next