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 sizbut on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

OLE Automating Excel from Access VBA

Status
Not open for further replies.

Bug16

Technical User
Oct 2, 2002
22
GB
I'm pretty new to OLE Automation so bear with me!

I'm intending to create a complex Excel spreadsheet that I want to pump values from Access into on a cell by cell basis.

I've created a quick Access VBA test project that opens my .xls file "oletest", changes focus in Excel to "Sheet1" and pumps a hardcoded value into cell (1,1). It then saves the .xls file under another name and attempts to tidy itself up:

Set xlObject = CreateObject("excel.application")
xlObject.Visible = True
xlObject.Application.Workbooks.Open "c:\oletest.xls"
Worksheets("Sheet1").Activate
Worksheets("Sheet1").Cells(1, 1).Value = "Test 123"
Worksheets("Sheet1").SaveAs ("c:\anothertest.xls")
xlObject.Application.Workbooks.Close
xlObject.Quit

The problem I have is that the first time I run the project it works. The second time I get:

"Run-time error '1004':

Method 'Worksheets' of object '_Global' failed"

This is caused by the line:

Worksheets("Sheet1").Activate

If I click on help nothing happens.

I'm assuming that I'm not tidying up Excel properly when I close it down but I have no idea what else I should be doing.

Help as always is appreciated! :)
 
Bug16,

Try this...

Private Sub Command0_Click()
Set xlobject = CreateObject("excel.application")
xlobject.Visible = True
xlobject.Application.Workbooks.Open "c:\oletest.xls"
Windows("oletest.xls").Activate
Worksheets("Sheet1").Activate
Worksheets("Sheet1").Cells(1, 1).Value = "Test 123"
Worksheets("Sheet1").SaveAs ("c:\anothertest.xls")
xlobject.Application.Workbooks.Close
xlobject.Quit
xlobject = ""

End Sub -illini
 
Bug16,

Actually, look at the line just above the highlighted.

Windows("oletest.xls").Activate -illini
 
Hmmm... I now get a new error when I run the project for a second time! :)

"Run-time error '9':

Subscript out of range"

And it debugs to your Windows("oletest.xls").Activate code.

Now I understand this error in a "normal" coding sense but with regard to OLE I'm guessing that the Windows object doesn't exist once the project has been run and we're trying to activate a non-existent object?
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top