简体   繁体   中英

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

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.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM