2017-05-23 188 views
2

我需要循環代碼有助於一個小區從R列複製並粘貼到下一個空單元列CExcel VBA中循環代碼

塔C

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

R列

1 

2 

3 

我用這個代碼,但是當我有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 
+0

至少給它一個嘗試,使用'for'循環。你可以在這裏找到一個相當簡單的例子:http://www.excel-easy.com/vba/loop.html – Noceo

回答

0

試試這個:

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 

一般情況下,這是我們所擁有的:

  • 集合colToPaste,其中包含範圍B1:B5的所有值。您可以根據列B中的最後一行更改收集範圍並將其設置爲變量。看到這裏 - https://www.rondebruin.nl/win/s9/win005.htm
  • 循環經過範圍A1:A500,它將檢查每個單元格是否爲空。如果它是空的,它會給它列表中第一個值 - rngCell = colToPaste(1)。然後它會刪除它。
  • 爲了知道何時停止,我添加了如果colToPaste.Count = 0 Then Exit Sub=0部分可以刪除,但這樣更容易理解。

enter image description here

+0

謝謝soooooooo它運作得很好 – kinroh

+0

我知道..... :) – Vityata