简体   繁体   中英

Excel macro to copy range from one sheet to another

I've got a problem with copying range from one sheet to another. Im trying to do it with code below

Sub zaladuj()
    Dim PND, DR As Worksheet
    Set PND = ActiveWorkbook.Sheets("sheet2")
    Set DR = ActiveWorkbook.Sheets("sheet1")
    Dim row As Integer
    Dim copyRng As Range, pasteRng As Range

    row = 4
    Do Until IsEmpty(DR.Cells(row, 2))
        row = row + 1
    Loop
    With DR
         Set copyRng = Range(Cells(3, 1), Cells(row, 5))
    End With

    With PND
        Set pasteRng = Range(Cells(3, 1), Cells(row, 5))
    End With

    copyRnd.Copy pasteRng

End Sub

However after running macro, nothing happens. As far as I noticed, whole functions runs only in sheet2. Whole macro is placed in sheet2 objects.

With on its own does nothing. You need the dots in front of the rangest to tie them to the object following the With statement.

Option Explicit

Sub zaladuj()
    Dim PND As Worksheet, DR As Worksheet
    Set PND = ActiveWorkbook.Sheets("sheet2")
    Set DR = ActiveWorkbook.Sheets("sheet1")
    Dim row As Long
    Dim copyRng As Range, pasteRng As Range

    row = 4
    Do Until IsEmpty(DR.Cells(row, 2))
        row = row + 1
    Loop
    With DR
         Set copyRng = .Range(.Cells(3, 1), .Cells(row, 5))
    End With

    With PND
        Set pasteRng = .Range(.Cells(3, 1), .Cells(row, 5))
    End With

    copyRng.Copy pasteRng

End Sub

Note also that

Dim PND, DR As Worksheet

declares PND as Variant - see amendment above.


Use Long rather than Integer as Excel has many more rows than Integer can handle.


You can probably replace with your Do loop with

row=DR.Cells(rows.count, 2).end(xlup).row

Is this what to do expect?

EDITED CODE

Option Explicit

Sub zaladuj()

    Dim PND As Worksheet, DR As Worksheet
    Dim row As Long

    With ThisWorkbook
        Set DR = .Sheets("Sheet1")
        Set PND = .Sheets("Sheet2")
    End With

    row = 4

    Do Until IsEmpty(DR.Cells(row, 2))

        DR.Range(DR.Cells(3, 1), DR.Cells(row, 5)).Copy PND.Range(PND.Cells(3, 1), PND.Cells(row, 5))

        row = row + 1

    Loop

End Sub

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