简体   繁体   中英

Excel vba copying sheets different workbook format

Can anyone assist explaining why my range does not update completely and how I can force that? The range of cells updates but the focus remains on the same sheet. It then fails when it reaches the next line where it has to copy.

        Workbooks.Open Filename:="U:\T\A.xlsx", UpdateLinks:=xlUpdateLinksNever

    dblLastRow = 1 + Workbooks("A.xlsx").Worksheets("Z").Cells(Rows.Count, 1).End(xlUp).Row

    Set rngReport2 = Workbooks("A.xlsx").Worksheets("Report2").Range(Cells(1, 1), Cells(dblLastRow, 7))
    rngReport2.Copy
    Workbooks("B.xls").Worksheets("Y").Range("A1").PasteSpecial (xlPasteValues)


    dblLastRow = Workbooks("A.xlsx").Worksheets("Sector code").Cells(Rows.Count, 1).End(xlUp).Row

    Set rngReport2 = Workbooks("A.xlsx").Worksheets("Sector code").Range(Cells(1, 1), Cells(dblLastRow, 3))
    rngReport2.Copy
    Workbooks("B.xls").Worksheets("X").Range("A1").PasteSpecial (xlPasteValues)

You should always qualify your Cells() with a worksheet reference:

Sub test()

    Dim wbA As Workbook, wbB As Workbook
    Dim dblLastRow As Long

    Set wbA = Workbooks.Open(Filename:="U:\T\A.xlsx", UpdateLinks:=xlUpdateLinksNever)
    Set wbB = Workbooks("B.xls")

    With wbA.Worksheets("Report2")
        dblLastRow = 1 + .Cells(Rows.Count, 1).End(xlUp).Row
        CopyValues .Range(.Cells(1, 1), .Cells(dblLastRow, 7)), wbB.Worksheets("Y").Range("A1")
    End With

    With wbA.Worksheets("Sector code")
        dblLastRow = .Cells(Rows.Count, 1).End(xlUp).Row
        CopyValues .Range(.Cells(1, 1), .Cells(dblLastRow, 3)), wbB.Worksheets("X").Range("A1")
    End With

End Sub

Sub CopyValues(rngSrc As Range, rngDest As Range)
    rngDest.Cells(1).Resize(rngSrc.Rows.Count, _
             rngSrc.Columns.Count).Value = rngSrc.Value
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