将数据从工作表复制到另一个工作簿

时间:2015-09-03 18:58:22

标签: excel vba excel-vba

How to Copy data from one excel file to another file in different folder using VBA?

从上面的链接中我得到了我正在寻找的代码。 我的查询尚未解决。

我根据我的要求对代码进行了一些更改,但结果却是错误的。 下面提到的是我使用的代码。

Sub TransferDataV2() 'transfer stuff from this workbook to workbook 2
    Dim strPath2 As String
    Dim wbkWorkbook1 As Workbook
    Dim wbkWorkbook2 As Workbook

    'define paths and filenames
    strPath2 = "E:\Purchase Register 2015-16.xlsx"

    'open files
    Set wbkWorkbook1 = ThisWorkbook '### changed this
    Set wbkWorkbook2 = Workbooks.Open(strPath2)

    'copy the values across
    '### change the sheet and range to what you need
    wbkWorkbook1.Activate
    Range("A2").Select
    Range(Selection, Selection.End(xlDown)).Select
    Range(Selection, Selection.End(xlToRight)).Select
    Selection.SpecialCells(xlCellTypeVisible).Select
    Selection.Copy
    wbkWorkbook2.Worksheets("Sheet1").Activate
    Range("A2").Select
    Range(Selection, Selection.End(xlDown)).Select
    ActiveCell.Offset(1).Select
    ActiveCell.PasteSpecial

    'close the workbook
    wbkWorkbook2.Close (True)
End Sub

现在每当我更新此工作簿中的某些数据并尝试保存到另一个工作簿时,复制的数据都会替换strPath2 = "C:\put in this.xlsx"中已有的数据。 我需要的结果是复制的数据必须保存在put in this.xlsx中 但在桌子的最后。相反,此代码会复制数据并将其保存在A2:G5中。 Kinldy Advice

1 个答案:

答案 0 :(得分:0)

Selection.Copy尝试后:

wbkWorkbook2.Worksheets("Sheet1").Cells(wbkWorkbook2.Worksheets("Sheet1").UsedRange.Row + 1, 1).PasteSpecial

'close the workbook
wbkWorkbook2.Close (True)