Copy and Paste row by index number in Excel Macro

前端 未结 3 1926
清酒与你
清酒与你 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:19

    Range Copy and Paste

    Syntax

    Range().Copy [Destination]

    The square brackets indicate that Destination is an optional parameter. If you don't designate a Destination range it copies the selection to the clipboard. Otherwise it copies the first range directly to the new location.

    Change this line:

    .Rows(lastRow) = .Rows(i).Value

    To:

    .Rows(lastRow).copy .Rows(i)

    It's worth noting that

    .Rows(lastRow).copy .Cells(i, 1)

    Will also work. Excel will resize the Destination range to fit the new data.

    0 讨论(0)
  • 2021-01-14 10:31

    I assume that you want to copy Rows(i) and paste it as value in Rows(lastRow). So, you need to replace this line

     .Rows(lastRow) = .Rows(i).Value
    

    with these two lines:

    .Rows(i).Copy
    .Rows(lastRow).PasteSpecial xlPasteValues
    

    Or

    .Rows(lastRow).Copy
    .Rows(i).PasteSpecial xlPasteValues
    

    if you want to copy Rows(lastRow) and paste it as value in Rows(i).

    Edit:

    To paste everything (formulas + values + formats), use paste type as xlPasteAll.

    Reference: msdn

    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题