简体   繁体   English

Excel VBA循环代码

[英]Excel VBA loop code

I need help with loop code to copy one cell from column R and paste into next empty cell in column C. 我需要循环代码帮助,以从R列复制一个单元格并将其粘贴到C列的下一个空单元格中。

column C C栏

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

Column R R栏

1

2

3

I used this code but when I will have 500 records it seems impossible to repeat this code for 500 times. 我使用了这段代码,但是当我有500条记录时,似乎不可能重复执行此代码500次。

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

Try this: 尝试这个:

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

In general, this is what we have: 总的来说,这就是我们所拥有的:

  • a collection colToPaste , which contains all the values of the range B1:B5 . 集合colToPaste ,其中包含范围B1:B5所有值。 You can change the collection range and make it with variable, as per the last row in column B . 您可以按照B列的最后一行更改收集范围并使用变量进行更改。 See here - https://www.rondebruin.nl/win/s9/win005.htm 看到这里-https://www.rondebruin.nl/win/s9/win005.htm
  • A loop going through the range A1:A500, which would check for every cell, whether it is empty or not. 循环经过范围A1:A500,该循环将检查每个单元格是否为空。 If it is empty, it would give it the value of the first one in the list like this - rngCell = colToPaste(1) . 如果为空,则将为它提供列表中第一个值的值rngCell = colToPaste(1) Then it would remove it. 然后它将删除它。
  • In order to know when to stop, I have added If colToPaste.Count = 0 Then Exit Sub . 为了知道何时停止,我添加了如果colToPaste.Count = 0 Then Exit Sub The =0 part can be removed, but it is easier to understand it this way. =0部分可以删除,但是这样更容易理解。

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM