In most situations, developers who want to automate an
Office application should use
CreateObject (or
New) to start a new instance of the Office application. In some
cases, however, you may prefer to automate an Office application that is
already running, such as if the user previously started the Office application
or if you start the .exe file for the Office application by using code so that
you can specify command-line switches for the application. In order to automate
the running Office application, you must use
GetObject.
Steps to Reproduce Behavior
- Start Microsoft Visual Studio .NET.
- On the File menu, click New, and then click Project. Under Project types, click Visual Basic Projects, and then click Windows Application under Templates. Form1 is created by default.
- On the View menu, click Toolbox to display the toolbox, and then add a button to Form1.
- Double-click Button1. The code window for the form appears.
- In the code window, replace the following code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
End Sub
with:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim oExcel As Object
' Start a new instance of Microsoft Excel.
Shell("C:\Program Files\Microsoft Office\Office10\Excel.exe", _
AppWinStyle.MinimizedNoFocus)
' "Cannot create ActiveX component." occurs on the following line:
oExcel = GetObject(, "Excel.Application")
MsgBox(oExcel.Name, MsgBoxStyle.MsgBoxSetForeground)
oExcel = Nothing
End Sub
- Make sure that the location of the Excel.exe file is
correct in the code sample.
- Quit Microsoft Excel if it is already running.
- On the Debug menu, click Start.