将范围对象从一个工作簿复制到另一个工作簿

时间:2014-10-20 08:07:49

标签: excel-vba vba excel

我尝试将工作簿(使用vba-excel打开)复制到另一个工作簿(thisworkbook)

Public wbKA as workbook
Sub A()
Dim oExcel As Excel.Application
KAPath = ThisWorkbook.path & "\Data.xlsx"
Set oExcel = New Excel.Application
Set wbKA = oExcel.Workbooks.Open(KAPath)
...
End Sub

使用此代码:

Sub Get()
Dim LastRow As Long
    With wbKA.Worksheets("Sheet1")
        LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
        .Range(.Cells(5, 1), .Cells(LastRow, 1)).Copy
        .Range(.Cells(5, 1), .Cells(LastRow, 1)).Copy Destination:=ThisWorkbook.Worksheets("SheetB").Range("A6")

调试器突出显示行.Range(.Cells(5, 1), .Cells(LastRow, 1)).Copy Destination:=ThisWorkbook.Worksheets("SheetB").Range("A6")(黄色),错误为copy method could not be applyed to the range object。第一个复制方法(只是由我来检查是否在没有Destination部分的情况下发生错误)运行。我将代码复制到另一个工作簿,我将复制目标复制模式应用于一个工作簿,它正在工作。谁能告诉我,为什么这不起作用? wbKA工作簿打开很好,我可以实际执行我需要的所有内容(搜索,将值粘贴到数组中等等),只是复制内容不起作用。

1 个答案:

答案 0 :(得分:1)

由于您使用的是Excel,因此无需打开新实例。那就是创建副本问题。试试这个(未经测试)

Sub Sample()
    Dim thisWb As Workbook, thatWb As Workbook
    Dim thisWs As Worksheet, thatWs As Worksheet
    Dim KAPath As String
    Dim LastRow As Long

    Set thisWb = ThisWorkbook
    Set thisWs = thisWb.Sheets("SheetB")

    KAPath = ThisWorkbook.Path & "\Data.xlsx"

    Set thatWb = Workbooks.Open(KAPath)
    Set thatWs = thatWb.Sheets("Sheet1")

    With thatWs
        LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row

        .Range(.Cells(5, 1), .Cells(LastRow, 1)).Copy thisWs.Range("A6")
    End With
End Sub

通过评论进行跟进。

使用不同的Excel实例时,无法使用rng.copy Dest.rng。您必须先复制它,然后粘贴到下一行。见这些例子

这不起作用

Sub Sample()
    Dim xl As New Excel.Application
    Dim wb As Workbook
    Dim ws As Worksheet

    xl.Visible = True
    Set wb = xl.Workbooks.Add
    Set ws = wb.Sheets(1)

    ws.Range("A1").Value = "Sid"

    ws.Range("A1").Copy ThisWorkbook.Sheets(1).Range("A1")
End Sub

这将有效

Sub Sample()
    Dim xl As New Excel.Application
    Dim wb As Workbook
    Dim ws As Worksheet

    xl.Visible = True
    Set wb = xl.Workbooks.Add
    Set ws = wb.Sheets(1)

    ws.Range("A1").Value = "Sid"

    ws.Range("A1").Copy
    ThisWorkbook.Sheets(1).Range("A1").PasteSpecial xlValues
End Sub