Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Running VBA Excel from VB 2

Status
Not open for further replies.

tatochka

Programmer
May 3, 2001
49
US
I need to run Excel application from VB6 application. When I run my Excel application just from Excel it works fine, but when I try to run it from VB6 application I get error message.

Here is the code of VB that runs on button's click:
Code:
    Dim ExcelApp As Excel.Application
    Dim ExcelWkb As Excel.Workbook
    Dim ExcelSht As Excel.Worksheet

    On Error Resume Next
    Err.Clear

    Set ExcelApp = GetObject("H:\Asset Management   
                        Code\ExcelBudget\Budget0515.xls")

    ExcelApp.Visible = True
I get the application started just fine, but then when I click one of the button I get an error message "Run-time error 91. Object or With block variable not set" with the statement highlited in excel:

Sheets("AdministrativeExpenses").Activate
I never got this message when I ran it from VBA Excel.
Can somebody help me here?
 
Using the GetObject method, you need to declare the ExcelApp as generic Object rather than an Excel Application. The GetObject method can not open a specific file.

Set xlApp = GetObject(,"Excel.Application")

This attaches to the Excel application, assuming it is running. You can use the CreateObject method to open a new instance.
Code:
On Error Resume Next

Set xlApp = GetObject(,"Excel.Application")
If Err.Number <> 0 then
    Err.Clear
    Set xlApp = CreateObject(&quot;Excel.Application&quot;)
End If

On Error Goto ErrHndlr

If you just want to open a workbook from VB, this may be a little easier. Make sure to add the Microsoft Excel Object Library to your project references.
Code:
Workbooks.Open FileName:=ModelPath & &quot;CtrClsrData.XLS&quot;
Workbooks.Application.Visible = True

 
The GetObject with an .XLS file name should return an Excel.Workbook object not the Application.
Whatever. Try this link
Code:
GetObject([pathname] [, class])

The GetObject function syntax has these named arguments

Part
 Description
 

 
pathname
 Optional; Variant (String). The full path and name of the file containing the object to retrieve. If pathname is omitted, class is required.
 
class
 Optional; Variant (String). A string representing the class of the object.
 
Wow, it did work. Thank you dsi. May be you can also tell me why the following code only closes the file but doesn't quit an excel itself:

Workbooks(&quot;Budget0515.XLS&quot;).Close SaveChanges:=True
Excel.Application.Quit
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top