问题
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 = "D:\File2.xls"
Windows(File1).Activate
Sheets("Name of Sheet").Select
Sheets("Name of Sheet").Copy Before:=Workbooks(File2).Sheets("Name of Target Sheet")
This is not working. I need to copy in background.Also to disable any macros.
- How can I make it work?
- Can I give instead of "Sheet Name" an index?
- Can I give an array of indexes to copy to the second Workbook?
回答1:
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
回答2:
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.
来源:https://stackoverflow.com/questions/11578569/how-to-copy-sheets-from-a-workbook-to-another-workbook