0

this vba code to loop through and copy and paste a new line every until it finds a zero keeps giving me a Run-time error '1004'. I can't quite figure out what is causing it. It breaks at Sheets("Regular Invoice").Range("A29:N29").Copy (According to using the F8 key) Any help is greatly appreciated.

Sub BoxTest()

Dim testRow As Integer
Dim pasteRow As Integer


testRow = 2
pasteRow = 30
Worksheets("Boxes").Select
Do Until Worksheets("Boxes").Range(testRow, 13).Value = 0

Sheets("Regular Invoice").Range("A29:N29").Copy
Worksheets("Regular Invoice").Cells(pasteRow, 1).PasteSpecial xlPasteAll

testRow = testRow + 1
pasteRow = pasteRow + 1

Loop
testRow = testRow + 1
pasteRow = pasteRow + 1


End Sub
0

2 Answers 2

3

This line is the problem

Do Until Worksheets("Boxes").Range(testRow, 13).Value = 0

you can do either

Do Until Worksheets("Boxes").Cells(testRow, 13).Value = 0

or

Do Until Worksheets("Boxes").Range("M" & testRow).Value = 0

Only Cells takes the range as Row Number and Column Number.

Range Only takes number as Row, and Columns always have to be Letter

Sign up to request clarification or add additional context in comments.

1 Comment

This was a working solution, thanks for the explanation on cells and range. Really helpful.
1

While @MutjayLee has already an excellent answer I'd still like to throw in this additional solution for your consideration:

Sub BoxTest()

Dim testRow As Integer
Dim pasteRow As Integer
Dim lngLastRow As Long

pasteRow = 30

With ThisWorkbook.Worksheets("Boxes")
    .Activate
    lngLastRow = .Cells(.Rows.Count, 13).End(xlUp).Row
    For testRow = 2 To lngLastRow
        If .Cells(testRow, 13).Value = 0 Then Exit For
        With ThisWorkbook.Sheets("Regular Invoice")
            .Range("A29:N29").Copy Destination:=.Cells(pasteRow, 1)
        End With
        pasteRow = pasteRow + 1
    Next testRow
End With

'Not really necessary
'testRow = testRow + 1
'pasteRow = pasteRow + 1

End Sub

It avoids the Do ... Loop and exchanges it with a For ... Next with the option to exit beforehand if your condition is met. These loops are normally preferred as they are definite and not indefinite as Do ... Loop. If the condition is incorrectly set for a Do ... Loop they can easily run indefinitely and crash your Excel.

2 Comments

I believe that this does work, but it just won't seem to work for me. I keep receiving error 1004 when I try to run this.
Sorry, I did it again and used Range when there should have been Cells. I corrected the error. Now it should work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.