[英]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: 总的来说,这就是我们所拥有的:
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 rngCell = colToPaste(1)
. rngCell = colToPaste(1)
。 Then it would remove it. 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.