jhenya-d
jhenya-d

Reputation: 399

UFT/QTP CreateObject Syntax error

I try to create object in UFT:

Dim xlApp 
Dim xlBook 
Dim xlSheet 
Set xlApp = CreateObject("Excel.Application")
Set xlBook = xlApp.Workbooks.Open("C:\1.xls")
Set xlSheet = xlBook.Sheets(1)

Creating fails with Syntax error in

The test run cannot continue due to a syntax error.
Syntax error
Line (242): Set xlApp = CreateObject("Excel.Application")

Does anybody know how to repair it? Thanks for the help

Upvotes: 0

Views: 1706

Answers (1)

TheBlastOne
TheBlastOne

Reputation: 4320

According to your comment, you are using somthing like:

Class MyClass
    Dim xlApp 
    Dim xlBook 
    Dim xlSheet 

    Set xlApp = CreateObject("Excel.Application")
    Set xlBook = xlApp.Workbooks.Open("C:\1.xls")
    Set xlSheet = xlBook.Sheets(1)
End Class

Then, you get a syntax error in the xlApp assignment.

And right so, because the assignment is invalid in that scope (which is no callable scope at all).

First of all, set option explicit on.

Then, make sure you define all instance variables with Dim.

Also, create a constructor, or as in the following sample, a callable Sub, which initializes the instance variables, like this:

Option Explicit

Class MyClass
    Dim xlApp 
    Dim xlBook 
    Dim xlSheet 
    Public Function SetParam ()
        Set xlApp = CreateObject("Excel.Application")
        Set xlBook = xlApp.Workbooks.Open("C:\1.xls")
        Set xlSheet = xlBook.Sheets(1)
    End Function
End Class

This would not generate a syntax error, and might be closer to what you intended.

This is because inside a Class...End Class construct, you cannot have anything else but definitions. No statements. And assignments are statements. (Initialization using "=" in a variable definition is not supported by VBScript.)

Upvotes: 5

Related Questions