2017-08-23 115 views
1

返回對象時,對象變量或與塊變量未設置錯誤我想使用應返回Excel.Application對象的函數:的Excel VBA:從功能

Dim ExcelApp As Object 
Set ExcelApp = getExcelApp() 



Function getExcelApp() As Object 
     Dim ExcelApp As Object 
     Set ExcelApp = CreateObject("Excel.Application") 
     ExcelApp.Visible = False 
     ExcelApp.ScreenUpdating = False 
     ExcelApp.DisplayAlerts = False 
     ExcelApp.EnableEvents = False 

     getExcelApp = ExcelApp 
End Function 

但我得到一個object variable or with block variable not set錯誤。什麼是錯的,如何完成我想要的?

回答

3

錯誤是因爲您錯過了Set command(這是因爲您正在分配對象而需要)。

但是,您正在創建一個對象,設置它,然後將其分配給不同的對象以便返回。您可以直接將所有內容直接分配給返回變量。
更簡潔的功能是:

Function getExcelApp() As Object 
    Set getExcelApp = CreateObject("Excel.Application") 
    With getExcelApp 
     .Visible = False 
     .ScreenUpdating = False 
     .DisplayAlerts = False 
     .EnableEvents = False 
    End With 
End Function 
3

Set的對象,所以set getExcelApp = ExcelApp

此外,如果您是從Excel中調用這個,那麼你就已經有了正確的類庫提供,所以我會用

Function Get_Excel() As Excel.Application 

Set Get_Excel = New Excel.Application 
Get_Excel.Visible = True 
'  etc, etc 
End Function 
2

嘗試像這:

Option Explicit 

Public Sub TestMe() 

    Dim ExcelApp As Object 
    Set ExcelApp = getExcelApp() 
    Debug.Print ExcelApp.Name 

End Sub 

Function getExcelApp() As Object 

    Dim ExcelApp As Object 
    Set ExcelApp = CreateObject("Excel.Application") 
    ExcelApp.Visible = True 
    ExcelApp.ScreenUpdating = False 
    ExcelApp.DisplayAlerts = False 
    ExcelApp.EnableEvents = False 

    Set getExcelApp = ExcelApp 

End Function 

它會打印新的ExcelApp的名稱。在這種情況下Microsoft Excel。我也將ExcelApp.Visible更改爲True,並且返回對象的函數應與Set一致。