Copy and Paste row by index number in Excel Macro

前端 未结 3 1931
清酒与你
清酒与你 2021-01-14 09:39

I\'m trying to copy an entire row by index number and paste it to another row with a different index number when a certain condition is met (I know the issue is not with the

3条回答
  •  情话喂你
    2021-01-14 10:42

    your code works for me

    so just add a breakpoint at .Rows(lastRow) = .Rows(i).Value statement and then query all relevant variables value in the Immediate Window, like:

    ?lastRow
    ?.Rows(lastRow).Address
    ?i
    ?.Rows(i).Address
    

    in the meanwhile you could

    • add Option Explicit statement at the very top of your code module

      this will force you to declare all variables and thus lead to some extra work, but you'll get repaid with much more control over your variables usage and misspelling, thus saving debugging time

    • dim variables to hold rows index as of Long type, to handle rows index higher then 32767

    • avoid inner loop using the Resize() method of range object

    much like follows:

    Option Explicit
    
    Sub Makro1()
    
        Dim i As Long, totalRows As Long, lastRow As Long, Number As Long
    
        With ActiveSheet
            'for looping
            totalRows = .Cells(.Rows.Count, "A").End(xlUp).Row
    
            'index of row to add from
            lastRow = totalRows + 1 '<--| start pasting values one row below the last non empty one in column "A"
    
            'data starts at row #3
            For i = 3 To totalRows
                If .Cells(i, 19).Value > 0 Then
                    Number = .Cells(i, 19).Value
                    .Rows(lastRow).Resize(Number).Value = .Rows(i).Value
                    lastRow = lastRow + Number
                End If
            Next i
        End With
    End Sub
    

提交回复
热议问题