How to copy sheets from a workbook to another workbook

前端 未结 2 485
名媛妹妹
名媛妹妹 2021-01-28 04:40

I have this code to copy a sheet from a Workbook in VBA/Access to another Workbook/File.

Dim File1 as String
Dim File2 as String
File1 = \"D:\\File1.xls\"
File2          


        
相关标签:
2条回答
  • 2021-01-28 04:55

    You need to open the workbooks first.

    Dim File1 As String
    Dim File2 As String
    File1 = "C:\Path\to\file\Book13.xlsx"
    File2 = "C:\Path\to\file\Book2.xlsx"
    
    Workbooks.Open Filename:=File2
    Workbooks.Open Filename:=File1
    ActiveWorkbook.Worksheets("Sheet2").Select
    Sheets("Sheet1").Copy Before:=Workbooks("Book2").Sheets(1)
    

    You can use the sheet name or an index with the Sheets object. To copy multiple worksheets into another workbook you can pass an array into a loop.

    0 讨论(0)
  • 2021-01-28 04:57

    If you are running in MS Access, you need something on these lines:

    Dim CopyFrom As Object
    Dim CopyTo As Object ''Early binding: Workbook
    Dim CopyThis As Object
    Dim xl As Object ''Early binding: New Excel.Application
    
    ''Late binding
    Set xl = CreateObject("Excel.Application")
    xl.Visible = True
    
    ''To use a password: Workbooks.Open Filename:="Filename", Password:="Password"
    Set CopyFrom = xl.Workbooks.Open("z:\docs\From.xls")
    Set CopyThis = CopyFrom.Sheets(1) ''Sheet number 1
    Set CopyTo = xl.Workbooks.Open("z:\docs\To.xls")
    CopyThis.Copy After:=CopyTo.Sheets(CopyTo.Sheets.Count)
    
    CopyFrom.Close False
    
    0 讨论(0)
提交回复
热议问题