如何将工作簿中的工作表复制到另一个工作簿

时间:2012-07-20 11:36:58

标签: excel vba ms-access ms-access-2010

我有这段代码将工作表从VBA / Access中复制到另一个工作簿/文件。

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")

这不起作用。 我需要在后台复制。也禁用任何宏。

  1. 我怎样才能让它发挥作用?
  2. 我可以代替“工作表名称”作为索引吗?
  3. 我可以提供一系列索引来复制到第二个工作簿吗?

2 个答案:

答案 0 :(得分:2)

如果您在MS Access中运行,则需要以下几行:

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

答案 1 :(得分:0)

您需要先打开工作簿。

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)

您可以使用工作表名称或Sheets对象的索引。要将多个工作表复制到另一个工作簿,您可以将数组传递给循环。