活頁簿檔案之間的工作表複製, 基本上有三個方法:
(一) 整張工作表的複製:
例如要把 Book2.xls 的 sheet3 複製到 Book3 裡, 插入 Sheet2 的前面:
(Book3和 Book2.xls 都是在檔案已開啟的狀態)
Workbooks("Book2.xls").Sheets("Sheet3").Copy before:=Workbooks("Book3").Sheets("Sheet2")
(二) 整張工作表所有儲存格的 "複製-貼上"
例如要把 Book2.xls 的 sheet3 複製到 Book3 的 Sheet2 裡面:
(Book3和 Book2.xls 都是在檔案已開啟的狀態)
Workbooks("Book2.xls").Worksheets("sheet3").Cells.Copy
Workbooks("Book3").Worksheets("sheet2").Paste
(三) 把 Excel 活頁簿當成來源資料庫:
假設要匯入 "C:\Book2.xls" 的 "sheet3", 不需開啟 "C:\Book2.xls" :
Sub 工作表匯入()
ActiveWorkbook.Worksheets.Add
With ActiveSheet.QueryTables.Add(Connection:=Array( _
"OLEDB;Provider=Microsoft.Jet.OLEDB.4.0;Password="""";User ID=Admin;Data Source=C:\Book2.xls;Mode=Share Deny Write;Extended Properties=""H" _
, _
"DR=NO;"";Jet OLEDB:System database="""";Jet OLEDB:Registry Path="""";Jet OLEDB:Database Password="""";Jet OLEDB:Engine Type=35;Jet OLED" _
, _
"B:Database Locking Mode=0;Jet OLEDB:Global Partial Bulk Ops=2;Jet OLEDB:Global Bulk Transactions=1;Jet OLEDB:New Database Passwo" _
, _
"rd="""";Jet OLEDB:Create System Database=False;Jet OLEDB:Encrypt Database=False;Jet OLEDB:Don't Copy Locale on Compact=False;Jet O" _
, "LEDB:Compact Without Replica Repair=False;Jet OLEDB:SFP=False"), Destination _
:=Range("A1"))
.CommandType = xlCmdTable
.CommandText = Array("Sheet3$")
.Name = "Book2"
.FieldNames = False
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.PreserveColumnInfo = True
.SourceDataFile = "C:\Book2.xls"
.Refresh BackgroundQuery:=False
End With
End Sub