2015-03-13 66 views
2

我需要在同一模塊中的其他程序中使用excel對象(在一個過程中設置)。但無法做到這一點。請幫助我也這樣做。以下是我的代碼。如何在excel中使用excel對象到另一個程序

Public Sub FirstProc() 'Here the excel object is defined 

Set xlApp = CreateObject("Excel.Application") 
Set xlWorkbook = xlApp.Workbooks.Open(ReportTemplateDirectory\Test.xlsx") 
xlApp.Visible = True 
... 
... 'all work goes here FINE 
... 

SecondProc 'calling second proc 
End Sub 

下面是我的第二個過程,

Public Sub SecondProc() 

' In this procedure i need to delete a sheet of the same excel file which is generated in above procedure. 

xlWorkbook.Sheets(4).Delete 

End Sub 

但我得到的運行時錯誤424必選對象。任何幫助,將不勝感激。

回答

3

雖然我只是將該行添加到第一個模塊,您可以嘗試這樣的事情(在Outlook中測試)。

DisplayAlerts已關閉以避免在工作表被刪除時發出檢查消息。

Public Sub FirstProc() 'Here the excel object is defined 

Dim xlApp As Object 
Dim xlWorkbook As Object 

Set xlApp = CreateObject("Excel.Application") 
xlApp.displayalerts = False 
Set xlWorkbook = xlApp.Workbooks.Add 
xlApp.Visible = True 

Call SecondProc(xlWorkbook) 'calling second proc 
xlApp.displayalerts = True 
End Sub 


Public Sub SecondProc(xlWorkbook As Object) 
' In this procedure i need to delete a sheet of the same excel file which is generated in above procedure. 
xlWorkbook.Sheets(2).Delete 
End Sub 
相關問題