[英]Using Access 2010 VBA list all open Excel Workbooks
好吧,我一定在這里缺少一些細微的東西。
在Excel 2010中,此VBA可以運行:
Private Sub ExcelTest()
Dim wb As Workbook
For Each wb In Workbooks
Debug.Print wb.Name
Next wb
End Sub
我正在嘗試在Access VBA中復制它,並且在Access 2010中嘗試了以下方法,但均未成功。
Private Sub AccessTest1()
'Derived from http://stackoverflow.com/questions/15958061/controlling-excel-
'workbook-from-access-2010-vba
Dim xlApp As Excel.Application
Dim xlWB As Excel.Workbook
Set xlApp = New Excel.Application
For Each xlWB In Excel.Workbooks
Debug.Print xlWB.Name
Next xlWB
'Nothing happens.
'Stepping through and hovering:
'xlApp = "MicroSoft Excel"
'xlWB = Nothing
'xlWB.Name = Object variable or With block variable not set.
'But doesn't throw an error.
End Sub
Private Sub AccessTest2()
'Derived from http://stackoverflow.com/questions/5729195/how-to-refer-to-excel-
'objects-in-access-vba
Dim xlApp As Excel.Application
Dim wb As Excel.Workbook
Set xlApp = New Excel.Application
For Each wb In Excel.Workbooks '<--- Like this nothing happens
Debug.Print wb.Name
Next wb
'Stepping through and hovering:
'xlApp = "MicroSoft Excel"
'wb = Nothing
'wb.Name = Object variable or With block variable not set. But doesn't throw an error.
For Each wb In xlApp.Workbooks '<--- This throws a "Object variable or
'With block variable not set" error
Debug.Print wb.Name
Next wb
End Sub
Private Sub AccessTest3()
'Derived from http://stackoverflow.com/questions/5729195/how-to-refer-to-excel-
'objects-in-access-vba
Dim objExcelApp As Object
Dim wb As Object
Set objExcelApp = CreateObject("Excel.Application")
Set wb = objExcelApp.Workbook '<--- Throws "Object doesn't support this property
'or method error"
'Hovering after error:
'objExcelApp = "MicroSoft Excel"
'wb = Nothing
For Each wb In objExcelApp.Workbooks
Debug.Print wb.Name
Next wb
End Sub
我肯定在Access中檢查了“ Microsoft Excel 14.0對象庫”參考。 我只是想列出所有打開的Excel工作簿,以便我可以對這些信息采取行動。 感謝您的幫助。
設置xlApp = New Excel.Application創建一個新的Excel實例-當然您那里沒有任何工作簿。
您想要達到的目標是通過一個已經打開的Excel實例。 因此,您必須使用getObject()。
For語句中還有另一個錯誤...您必須使用xlApp.Workbooks而不是Excel.Workbooks。
以下代碼應提供正確的結果:
Dim xlApp As Excel.Application
Set xlApp = GetObject(, "Excel.Application")
Dim xlWB As Excel.Workbook
For Each xlWB In xlApp.Workbooks
Debug.Print xlWB.Name
Next xlWB
Set xlApp = Nothing
Set xlWB = Nothing
最后,請記住通過將對象變量設置為Nothing來取消對它們的嘗試。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.