Microsoft KB Archive/306686

= How To Run Office Macros Using Automation From Visual C++ .NET =

Article ID: 306686

Article Last Modified on 6/29/2007

-

APPLIES TO


 * Microsoft Access 2002 Standard Edition
 * Microsoft Excel 2002 Standard Edition
 * Microsoft PowerPoint 2002 Standard Edition
 * Microsoft Word 2002 Standard Edition
 * Microsoft Visual C++ .NET 2002 Standard Edition
 * Microsoft Visual C++ .NET 2003 Standard Edition

-



This article was previously published under Q306686



For a Microsoft Visual Basic .NET version of this article, see 306682.

For a Microsoft Visual C# version of this article, see 306683.



SUMMARY
With Microsoft Office Automation, you can open a document or create a new document that contains a Visual Basic for Applications (VBA) macro and execute the macro at run time. This article demonstrates how to call Office macros from a Visual C++ .NET Automation client.



MORE INFORMATION
The following sample Automation client manipulates an Office Automation server (Access, Excel, PowerPoint or Word) based on your selection on a form. After the client starts the Automation server, it opens a document and then calls two macros. The first macro, DoKbTest, has no parameters and the second macro, DoKbTestWithParameter, takes a single parameter of type String.

Create Office Documents Containing Macros
 Create a Word document named C:\Doc1.doc. To do this, follow these steps:  In Word, create a new document. Press ALT+F11 to open the Visual Basic Editor. On the Insert menu, click Module.  Paste the following macro code into the new module: 'Display a message box that displays the application name. Public Sub DoKbTest MsgBox &quot;Hello from &quot; & Application.Name End Sub

'Display a message box with the string passed from the 'Automation client. Public Sub DoKbTestWithParameter( sMsg As String ) MsgBox sMsg End Sub  Close the Visual Basic Editor, save the Word document, and quit Word.</li></ol> </li> Create an Excel workbook named C:\Book1.xls by using steps similar to those that you used to create the Word document.</li> Create a PowerPoint presentation named C:\Pres1.ppt by using steps similar to those that you used to create the Word document.</li> Create a new Access database named C:\Db1.mdb. To do this, follow these steps: <ol style="list-style-type: lower-alpha;"> On the Insert menu, click Module.</li> Paste the macro code in the new module.</li> Save the module and quit Access.</li></ol> </li></ol>

Create the Visual C++ .NET Automation Client
<ol> Start Microsoft Visual Studio .NET. On the File menu, click New and then click Project. Select Managed C++ Applicationfor Visual Studio .NET 2002 or Console Application (.NET) for Visual Studio .NET 2003 from the Visual C++ Projects types. Name the project OfficeMacros and create the project in C:\.</li> If you have not already done so, download, install, and then register the Microsoft Office XP Primary Interop Assemblies (PIAs). For additional information about Office XP PIAs, click the article number below to view the article in the Microsoft Knowledge Base:

328912 INFO: Microsoft Office XP PIAs Are Available for Download

Install the PIAs in C:\Program Files\Microsoft Visual Studio .NET\Enterprise Frameworks or another equally accessible folder. They will also be registered in the Global Assembly Cache.</li> Add the folder in which you installed the Primary Interop Assembly DLL files to the list of directories that are searched to resolve file references that are passed to the #using directive. To do this, follow these steps: <ol style="list-style-type: lower-alpha;"> In the Visual Studio .NET Solution Explorer pane, right-click the project and click Properties.</li> In the left pane of the Property Pages dialog box, click the C/C++ folder and then click the General folder.</li> In the Resolve #using References dialog box, add the C:\Program Files\Microsoft Visual Studio .NET\Enterprise Frameworks path, and then click OK. If you installed the PIAs in a different folder, use the full path to that folder, instead.</li></ol> </li>  Open OfficeMacros.cpp in the source editor and replace the contents with the following code: // This is the main project file for VC++ application project // generated using an Application Wizard.


 * 1) include &quot;stdafx.h&quot;

#using <mscorlib.dll>

#using &quot;Office.dll&quot; #using &quot;Microsoft.Office.Interop.word.dll&quot; #using &quot;Microsoft.Office.Interop.excel.dll&quot; #using &quot;Microsoft.Office.Interop.powerpoint.dll&quot; #using &quot;Microsoft.Office.Interop.Access.dll&quot; #using &quot;Microsoft.vbe.interop.dll&quot;

using namespace System; //using namespace System::Diagnostics; using namespace System::Reflection; using namespace Microsoft::Office::Core; using namespace Microsoft::Office::Interop;

#include <tchar.h>

void PrintMenu; void AutoCallAccess; void AutoCallExcel; void AutoCallPowerPoint; void AutoCallWord; void CallMacro(Object* oApp, Object* oArgs[]);

int _tmain(void) {   PrintMenu; String* s = Console::ReadLine; while( !s->ToLower->Equals(S&quot;q&quot;) ) {       Int32 i;        try {           i = Convert::ToInt32(s,10); }       catch( Exception* e ) {           goto print; }

// Select the Office application to automate based on user input.

switch( i ) {       case 1: AutoCallAccess; break; case 2: AutoCallExcel; break; case 3: AutoCallPowerPoint; break; case 4: AutoCallWord; break; default: ;       }   print: PrintMenu; s = Console::ReadLine; }   return 0; }

void PrintMenu {   Console::WriteLine(S&quot;\n\nEnter the number of the application you'd like to automate.&quot;); Console::WriteLine(S&quot;Enter 'q' to quit the application.\n&quot;); Console::WriteLine(S&quot;\t\t1. Microsoft Access&quot;); Console::WriteLine(S&quot;\t\t2. Microsoft Excel&quot;); Console::WriteLine(S&quot;\t\t3. Microsoft PowerPoint&quot;); Console::WriteLine(S&quot;\t\t4. Microsoft Word\n&quot;); Console::Write(S&quot;\tSelection:&quot;); }

void AutoCallAccess {   try{ //Start Access, make it visible, and open C:\Db1.mdb. Console::WriteLine(&quot;\nStarting Microsoft Access...&quot;); Access::ApplicationClass* pAccess = new Access::ApplicationClass; pAccess->Visible = true; pAccess->OpenCurrentDatabase(&quot;c:\\db1.mdb&quot;, false, &quot;&quot;); //Run the macros. System::Object* oParams[] = {new String(&quot;DoKbTest&quot;), System::Reflection::Missing::Value}; CallMacro(pAccess, oParams); oParams[0] = new String(&quot;DoKbTestWithParameter&quot;); oParams[1] = new String(&quot;Hello From Visual C++ .NET (AutoCallAccess)&quot;); CallMacro(pAccess, oParams); //Quit Access and clean up. pAccess->get_DoCmd->Quit(Access::AcQuitOption::acQuitSaveNone); System::Runtime::InteropServices::Marshal::ReleaseComObject(pAccess); GC::Collect; }   catch(Exception* e)    { Console::WriteLine(S&quot;Error automating Access...&quot;); Console::WriteLine(e->get_Message); }  }

void AutoCallExcel {   try{ //Start Excel, make it visible, and open C:\Book1.xls. System::Object* oMissing = System::Reflection::Missing::Value; Console::WriteLine(&quot;\nStarting Microsoft Excel...&quot;); Excel::ApplicationClass* pExcel = new Excel::ApplicationClass; pExcel->Visible = true; Excel::Workbooks* pBooks = pExcel->get_Workbooks; Excel::_Workbook* pBook = pBooks->Open(&quot;c:\\book1.xls&quot;, oMissing, oMissing,           oMissing, oMissing, oMissing, oMissing, oMissing, oMissing,             oMissing, oMissing, oMissing, oMissing, oMissing, oMissing);

//Run the macros. System::Object* oParams[] = {new String(&quot;DoKbTest&quot;), oMissing}; CallMacro(pExcel, oParams); oParams[0] = new String(&quot;DoKbTestWithParameter&quot;); oParams[1] = new String(&quot;Hello From Visual C++ .NET (AutoCallExcel)&quot;); CallMacro(pExcel, oParams); //Quit Excel and clean up. pBook->Close(false, oMissing, oMissing); System::Runtime::InteropServices::Marshal::ReleaseComObject(pBook); System::Runtime::InteropServices::Marshal::ReleaseComObject(pBooks); pExcel->Quit; System::Runtime::InteropServices::Marshal::ReleaseComObject(pExcel); GC::Collect; }   catch(Exception* e)    { Console::WriteLine(S&quot;Error automating Excel...&quot;); Console::WriteLine(e->get_Message); }  }

void AutoCallPowerPoint {   try{ //Start PowerPoint, make it visible, and open C:\Pres1.ppt. Console::WriteLine(&quot;\nStarting Microsoft PowerPoint...&quot;); PowerPoint::ApplicationClass* pPPT = new PowerPoint::ApplicationClass; pPPT->Visible = Microsoft::Office::Core::MsoTriState::msoTrue; PowerPoint::Presentations* pPresSet = pPPT->get_Presentations; PowerPoint::_Presentation* pPres = pPresSet->Open(&quot;C:\\pres1.ppt&quot;,            MsoTriState::msoFalse,             MsoTriState::msoFalse,            MsoTriState::msoTrue); //Run the macros. System::Object* oParams[] = {new String(&quot;'pres1.ppt'!DoKbTest&quot;), System::Reflection::Missing::Value}; CallMacro(pPPT, oParams); oParams[0] = new String(&quot;'pres1.ppt'!DoKbTestWithParameter&quot;); oParams[1] = new String(&quot;Hello From Visual C++ .NET (AutoCallPowerPoint)&quot;); CallMacro(pPPT, oParams); //Quit PowerPoint and clean up. pPres->Close; System::Runtime::InteropServices::Marshal::ReleaseComObject(pPres); System::Runtime::InteropServices::Marshal::ReleaseComObject(pPresSet); pPPT->Quit; System::Runtime::InteropServices::Marshal::ReleaseComObject(pPPT); GC::Collect; }   catch(Exception* e)    { Console::WriteLine(S&quot;Error automating PowerPoint...&quot;); Console::WriteLine(e->get_Message); }  }

void AutoCallWord {   try{ //Start Word, make it visible, and open C:\Doc1.doc. System::Object* oMissing = System::Reflection::Missing::Value; Console::WriteLine(&quot;\nStarting Microsoft Word...&quot;); Word::ApplicationClass* pWord = new Word::ApplicationClass; pWord->Visible = true; Word::Documents* pDocs = pWord->Documents; System::Object* oFile = new System::Object; oFile = S&quot;c:\\doc1.doc&quot;; Word::_Document* pDoc = pDocs->Open(&oFile, &oMissing,           &oMissing, &oMissing, &oMissing, &oMissing, &oMissing,            &oMissing, &oMissing, &oMissing, &oMissing, &oMissing,            &oMissing, &oMissing, &oMissing);

//Run the macros. System::Object* oParams[] = {new String(&quot;DoKbTest&quot;), oMissing}; CallMacro(pWord, oParams); oParams[0] = new String(&quot;DoKbTestWithParameter&quot;); oParams[1] = new String(&quot;Hello From Visual C++ .NET (AutoCallWord)&quot;); CallMacro(pWord, oParams); //Quit Word and clean up. pDoc->Close(&oMissing, &oMissing, &oMissing); System::Runtime::InteropServices::Marshal::ReleaseComObject(pDoc); System::Runtime::InteropServices::Marshal::ReleaseComObject(pDocs); pWord->Quit(&oMissing, &oMissing, &oMissing); System::Runtime::InteropServices::Marshal::ReleaseComObject(pWord); GC::Collect; }   catch(Exception* e)    { Console::WriteLine(S&quot;Error automating Word...&quot;); Console::WriteLine(e->get_Message); }  }

void CallMacro(Object* oApp, Object* oArgs[]) {   Console::WriteLine(&quot;Calling Macro...&quot;); oApp->GetType->InvokeMember(&quot;Run&quot;,       BindingFlags(BindingFlags::Default | BindingFlags::InvokeMethod),        NULL, oApp, oArgs);

}                   </li></ol>

Run and Test the Automation Client
<ol> Press F5 to build and run the Automation client.</li>  When the client runs, you are presented with the following selection: <pre class="fixed_text">Enter the number of the application you'd like to automate. Enter 'q' to quit the application.

1. Microsoft Access 2. Microsoft Excel 3. Microsoft PowerPoint 4. Microsoft Word

Selection: </li> At the prompt, type 1 and press ENTER. The Automation client starts Access, runs the macros in the database that you created, and then quits Access.</li> <li>Repeat the previous step to automate Excel, PowerPoint and Word.</li> <li>When finished, type q and press ENTER to quit the Automation client.</li></ol>

<div class="references_section">