如何使用下一个单元格的值重复代码直到空白

时间:2019-08-29 19:09:44

标签: excel vba

我对Excel VBA编码非常陌生,一直很难找出一个可以让我在下一行重复我的代码直到它变成空白的代码。

我试图获取单元格A7之后的数据工作表中的下一个值,因此它是A8,并重复该宏,直到到达空白单元格为止。

Sheets("data").Select
Range("A7").Select
Selection.Copy
Sheets("CODING BLOCK").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False
Sheets("CODING BLOCK").Select
Application.CutCopyMode = False
Sheets("CODING BLOCK").Copy Before:=Sheets(1)
ActiveSheet.Select
ActiveSheet.Name = ActiveSheet.Range("L1")

任何朝着正确方向的指导将不胜感激。

1 个答案:

答案 0 :(得分:0)

您需要循环遍历每一行。这样的事情可能会帮助您入门:

Sub test()
Dim LastRow As LongPtr  'LongPtr is compatible with 32 and 64 bit machines
Dim CurrRow As LongPtr 


CurrRow = 7  '<-- set your current row

' find the last non-empty cell in column A
With ActiveSheet
    LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
End With

' MsgBox LastRow <-- un-comment to print out last row

' loop over rows
Do While CurrRow <= LastRow
    ' your code here
    Sheets("data").Select
    Range("A" & CurrRow).Select  'use the CurrRow variable to select the correct cell
    Selection.Copy
    Sheets("CODING BLOCK").Select
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
    Sheets("CODING BLOCK").Select
    Application.CutCopyMode = False
    Sheets("CODING BLOCK").Copy Before:=Sheets(1)
    ' ActiveSheet.Select 
    ' ActiveSheet.Name = ActiveSheet.Range("L1") These two lines might be causing your blank sheet issue
    CurrRow = CurrRow + 1  'increment the CurrRow variable
Loop


End Sub

调试语句是您的朋友。我使用MsgBox是因为它会创建一个暂停执行的弹出窗口,但是如果您可以使用“即时”窗口,则debug.print也可以正常工作。