复制工作簿之间的范围

时间:2015-04-30 18:31:06

标签: excel vba excel-vba

我正在尝试将一个工作簿中的工作表上的一系列单元格复制到另一个工作簿中的工作表底部。我一直在复制线上获得“应用程序定义或对象定义的错误”。

Dim NewFileName As String
Dim BAHFileName As String

NewFileName = "Filename"
BAHFileName = "Other Filename"

LastRow = Sheets("All").UsedRange.Rows.Count
Workbooks(NewFileName).Sheets("All").Range(Cells(2, 1), Cells(LastRow, 15)).Copy

Windows(BAHFileName & ".xlsx").Activate
LastRow = Workbooks(BAHFileName).Sheets(1).UsedRange.Rows.Count + 1
Workbooks(BAHFileName).Sheets(1).Cells(LastRow, 1).Select
ActiveSheet.Paste
Application.CutCopyMode = False

2 个答案:

答案 0 :(得分:1)

我需要在复制前选择纸张。

Dim NewFileName As String
Dim BAHFileName As String

NewFileName = "Filename"
BAHFileName = "Other Filename"

LastRow = Sheets("All").UsedRange.Rows.Count
Sheets("All").Select
Workbooks(NewFileName).Sheets("All").Range(Cells(2, 1), Cells(LastRow, 15)).Copy

Windows(BAHFileName & ".xlsx").Activate
LastRow = Workbooks(BAHFileName).Sheets(1).UsedRange.Rows.Count + 1
Workbooks(BAHFileName).Sheets(1).Cells(LastRow, 1).Select
ActiveSheet.Paste
Application.CutCopyMode = False

答案 1 :(得分:1)

和自己说话?

练习使用此代码以避免使用选择。

我不确定您的工作簿的情况,因此您必须相应地调整工作簿名称和工作表名称。

Sub Button1_Click()
    Dim WB As Workbook
    Dim bk As Workbook
    Dim LastRow As Long
    Dim Lrow As Long
    Dim rng As Range
    Dim ws As Worksheet
    Dim sh As Worksheet

    Set WB = ThisWorkbook
    Set bk = Workbooks("MyWorkbook.xlsx")
    Set ws = WB.Sheets("All")
    Set sh = bk.Sheets(1)

    With ws
        LastRow = .UsedRange.Rows.Count
        Set rng = .Range(.Cells(2, 1), .Cells(LastRow, 15))
    End With

    With sh
        Lrow = .UsedRange.Rows.Count + 1
        rng.Copy .Cells(Lrow, 1)
    End With

End Sub