1
我一直在關注以下模式以使用Excel InterOp創建多個工作表和多個工作簿。現在,我需要創建一個讓我們稱之爲主工作簿的工作簿,其中包含我在原始工作簿中創建的工作表中的一些工作表。舉個例子,比如說WorkBook1有Sheet1和Sheet2,而Workbook2有Sheet3和Sheet4。我希望Master工作簿具有Sheet1和Sheet3。我正在尋找一種方法來創建我爲WorkBook1和WorkBook2創建的工作表(工作表1,工作表2,工作表3,工作表4),而且只需最少量的代碼重複將工作表1和工作表3添加到主工作簿。任何幫助將不勝感激。如何創建Excel工作表並將其添加到Excel中的多個工作簿InterOp
For i = 1 To 10
Dim xlApp As Application = New Application
Dim xlWorkBook As Workbook
xlWorkBook = xlApp.Workbooks.Add
Dim xlWorkSheet As Worksheet
Dim xlSheets As Sheets = xlWorkBook.Sheets
Dim xlNewSheet As Worksheet
Dim sheetCount As Integer = 1
' So I repeat the following block to add multiple sheets with different content to a WorkBook
xlNewSheet = xlSheets.Add(xlSheets(sheetCount), Type.Missing, Type.Missing, Type.Missing)
sheetCount += 1
xlNewSheet.Name = SomeName
xlWorkSheet = xlWorkBook.Sheets(SomeName)
AddContentToSheet(xlNewSheet) ' A Sub that adds real content to the sheet
.
.
.
.
xlWorkBook.SaveAs(...)
xlWorkBook.Close()
xlApp.Quit()
Next i
所以,現在,我的問題是,如果我有我的主簿:
Dim MasterWorkBook As Workbook
MasterWorkBook = xlApp.Workbooks.Add
一個重複10次創造10點不同的工作簿循環之前定義。如何以最少量的代碼重複將選擇的表格添加到MasterWorkBook中。
不要忘了[釋放你的COM對象](http://stackoverflow.com/questions/158706/how-to-properly-clean-up-excel-interop-objects)! – 2014-09-03 16:13:15