简体   繁体   中英

Do Until Loop Excel VBA

I am trying to create "Do Until" loop in Excel VBA where it copies each value populated in column A of "SQL" worksheet (starting in cell A2), pastes the value into cell "A2" of the "Home" worksheet, runs the "PDF" macro that already exists, continues this process for each populated value, and ends when there are no more values in column A of "SQL" worksheet. I'm very new to VBA, and tried coming with something from other posts/blog. Any help would be greatly appreciated.

Dim rngMyRange As Range, rngCell As Range
Dim sht As Worksheet
Dim LastRow As Long
Dim SheetName As String


With Worksheets("SQL")
Set rngMyRange = .Range(.Range("a2"), .Range("A1000").End(x1up))

Do Until IsEmpty(Cells(rowNo, 1))
  For Each rngCell In rngMyRange
  rngCell.Cells.Select
  Selection.Copy
  Sheets("HOME").Select
  Range("A2").Select
  ActiveSheet.Paste
  Application.CutCopyMode = False
  Application.Run "'PDF Generator.xlsm'!PDF"

Loop
End Sub

You have a for loop inside the Do loop. Remove the Do loop.

You never use End With

Also avoid the use of .Select and .Activate it slows the code:

Dim rngMyRange As Range, rngCell As Range


With Worksheets("SQL")
    Set rngMyRange = .Range(.Range("a2"), .Range("A1048576").End(xlup))
End With

For Each rngCell In rngMyRange
  rngCell.Copy
  Sheets("HOME").Range("A2").PasteSpecial
  Application.CutCopyMode = False
  Application.Run "'PDF Generator.xlsm'!PDF"
Next rngCell

Add a dot here:

Do Until IsEmpty(.Cells(rowNo, 1))

Without the dot it is refering to the activesheet.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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