1

I want to use a function that should return an Excel.Application Object:

 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

But I get a object variable or with block variable not set error. What is wrong and how to accomplish what I want?

3 Answers 3

3

The error is because you're missing the Set command (which is needed because you're assigning an object).

But you're creating one object, setting it up, then assigning it to a different object for returning. You could instead assign everything directly to the return variable.
A more concise function would be:

Function getExcelApp() As Object
    Set getExcelApp = CreateObject("Excel.Application")
    With getExcelApp
        .Visible = False
        .ScreenUpdating = False
        .DisplayAlerts = False
        .EnableEvents = False
   End With
End Function
Sign up to request clarification or add additional context in comments.

Comments

3

Set for objects, so set getExcelApp = ExcelApp

Also, If you are calling this from Excel, then you'll already have the correct class library available, so I'd use

Function Get_Excel() As Excel.Application

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

Comments

2

Try like this:

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

It would print the name of the new ExcelApp. In this case Microsoft Excel. I have also changed ExcelApp.Visible to True and the function, returning an object should be with a Set.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.