excelvba循环代码

excelvba循环代码,excel,vba,Excel,Vba,我需要有关循环代码的帮助,以便从列R复制一个单元格并粘贴到列C的下一个空单元格中 12345 12345 12345 (paste 1 in here) 12346 12346 (paste 2 in here) 12347 12347 12347 12347 (paste 3 in here) C列 1234

我需要有关循环代码的帮助,以便从列R复制一个单元格并粘贴到列C的下一个空单元格中

12345                      
12345                      
12345                      
(paste 1 in here)   
12346   
12346   
(paste 2 in here)   
12347   
12347   
12347   
12347   
(paste 3 in here)   
C列

12345                      
12345                      
12345                      
(paste 1 in here)   
12346   
12346   
(paste 2 in here)   
12347   
12347   
12347   
12347   
(paste 3 in here)   
R列

12345                      
12345                      
12345                      
(paste 1 in here)   
12346   
12346   
(paste 2 in here)   
12347   
12347   
12347   
12347   
(paste 3 in here)   
1

2

3
我使用了这个代码,但当我有500条记录时,似乎不可能重复这个代码500次

12345                      
12345                      
12345                      
(paste 1 in here)   
12346   
12346   
(paste 2 in here)   
12347   
12347   
12347   
12347   
(paste 3 in here)   
Range("R2").Select
Selection.Copy
Range("C1").Select

If IsEmpty(ActiveCell.Offset(1, 0)) Then
    ActiveCell.Offset(1, 0).Select
Else
    ActiveCell.End(xlDown).Offset(1, 0).Select
End If

Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
  :=False, Transpose:=False
试试这个:

12345                      
12345                      
12345                      
(paste 1 in here)   
12346   
12346   
(paste 2 in here)   
12347   
12347   
12347   
12347   
(paste 3 in here)   
Option Explicit

Public Sub CopyAndPaste()

    Dim colToPaste  As New Collection
    Dim rngCell     As Range

    With Worksheets(1)
        For Each rngCell In .Range("B1:B5")
            colToPaste.Add rngCell
        Next rngCell

        For Each rngCell In .Range("A1:A500")
            If IsEmpty(rngCell) Then
                If colToPaste.Count = 0 Then Exit Sub
                rngCell = colToPaste(1)
                colToPaste.Remove (1)
            End If
        Next rngCell
    End With

End Sub
总的来说,这就是我们所拥有的:

12345                      
12345                      
12345                      
(paste 1 in here)   
12346   
12346   
(paste 2 in here)   
12347   
12347   
12347   
12347   
(paste 3 in here)   
  • 一个集合
    colToPaste
    ,它包含范围
    B1:B5
    的所有值。您可以根据列
    B
    中的最后一行更改收集范围并使其具有变量。看这里-
  • 通过A1:A500范围的循环,检查每个单元格是否为空。如果它是空的,它将给出列表中第一个的值,如下-
    rngCell=colToPaste(1)
    。然后它会移除它
  • 为了知道何时停止,我添加了If
    colToPaste.Count=0,然后退出Sub
    =0
    部分可以删除,但这样更容易理解

至少尝试一下,使用
for
循环。您可以在这里找到一个相当简单的示例:
12345                      
12345                      
12345                      
(paste 1 in here)   
12346   
12346   
(paste 2 in here)   
12347   
12347   
12347   
12347   
(paste 3 in here)