Excel宏可将范围从一张纸复制到另一张纸

时间:2019-03-07 11:36:27

标签: excel vba range

将范围从一张纸复制到另一张纸时出现问题。我正在尝试使用下面的代码

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

但是在运行宏之后,什么也没有发生。据我所知,整个函数仅在sheet2中运行。整个宏放置在sheet2对象中。

2 个答案:

答案 0 :(得分:1)

With本身不执行任何操作。您需要在Rangest前面的点将它们与With语句之后的对象联系起来。

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

请注意

Dim PND, DR As Worksheet

PND声明为Variant-请参见上面的修订。


使用Long而不是Integer,因为Excel的行数多于Integer不能处理。


您可能可以用Do循环替换

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

答案 1 :(得分:0)

这是应该做什么?

编辑代码

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