我想使用一个应该返回Excel.Application
对象的函数:
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
错误。有什么不对,怎么做到我想要的?
答案 0 :(得分: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
答案 1 :(得分: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
答案 2 :(得分: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
。