How to copy sheets from a workbook to another workbook

天涯浪子 提交于 2019-12-24 23:25:15

问题


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.

  1. How can I make it work?
  2. Can I give instead of "Sheet Name" an index?
  3. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!