I
Ian Dunn
I'm simply trying to access an instance of Excel that has been opened
manually by the user in order to put a few values in the existing sheet.
Here's the code I've tried:
Dim oXL As Excel.Application
Dim oWB As Excel.Workbook
Dim oSheet As Excel.Worksheet
oXL = GetObject(, "Excel.Application")
oWB = oXL.ActiveWorkbook
oSheet = oWB.ActiveSheet
Unfortunately this doesn't work. What happens is that oXL.ActiveWorkbook
is "nothing" so the last line in this code fails when trying to access
it's ActiveSheet property.
The reason this happens seems to be that GetObject isn't getting the
existing Excel instance and is instead behaving exactly like
CreateObject and making a new instance with no workbooks. In fact
GetObject even works if Excel isn't currently running which I don't
think it's meant to. For example the following code (which is adapted
slightly from the help for GetObject):
oXL = GetObject(, "Excel.Application")
If Err().Number <> 0 Then
MsgBox("Excel was not running")
Else
MsgBox("Excel was running")
End If
This always reports that Excel was running even if it wasn't.
I'm using Visual Studio 2003 and have tried this with both Excel 2000,
and Excel 2003 with the same result.
Any idea what's going wrong or how I can do this properly?
Thanks
manually by the user in order to put a few values in the existing sheet.
Here's the code I've tried:
Dim oXL As Excel.Application
Dim oWB As Excel.Workbook
Dim oSheet As Excel.Worksheet
oXL = GetObject(, "Excel.Application")
oWB = oXL.ActiveWorkbook
oSheet = oWB.ActiveSheet
Unfortunately this doesn't work. What happens is that oXL.ActiveWorkbook
is "nothing" so the last line in this code fails when trying to access
it's ActiveSheet property.
The reason this happens seems to be that GetObject isn't getting the
existing Excel instance and is instead behaving exactly like
CreateObject and making a new instance with no workbooks. In fact
GetObject even works if Excel isn't currently running which I don't
think it's meant to. For example the following code (which is adapted
slightly from the help for GetObject):
oXL = GetObject(, "Excel.Application")
If Err().Number <> 0 Then
MsgBox("Excel was not running")
Else
MsgBox("Excel was running")
End If
This always reports that Excel was running even if it wasn't.
I'm using Visual Studio 2003 and have tried this with both Excel 2000,
and Excel 2003 with the same result.
Any idea what's going wrong or how I can do this properly?
Thanks