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

MS Word Automation 1

Status
Not open for further replies.

fdsouth

Technical User
Jun 6, 2001
61
US
I've created an application that does a "mail merge" to add text from a data file into a word document. I copied the code from the web and then modified it the best I could to meet my needs. I've got a simple question. How do I save the new document and close both it and MS Word automatically? I've included a snapshot of the code minus all the page formatting, etc:

Code:
void CMet_SampleDlg::OnRun() 
{

	_Application oWord;
	Documents oDocs;
	_Document oDoc;
	Selection oSelection;
	Paragraphs oParagraphs;
	Tables oTables;
	Table oTable;
	Range oRange;
	Columns oColumns;
	Column oColumn;
	Rows oRows;
	Row oRow;

	Cells oCells;
	Cell oCell; 
	Shading oShading;
	MailMerge oMailMerge;
	MailMergeFields oMailMergeFields;
	COleVariant vtOptional((long)DISP_E_PARAMNOTFOUND,VT_ERROR),
		        vtTrue((short)TRUE),
				vtFalse((short)FALSE);
	CString StrToAdd;

	// Create an instance of Word
	if (!oWord.CreateDispatch("Word.Application")) {
		AfxMessageBox("Word failed to start!");
	} else {
	// Set the visible property
	oWord.SetVisible(TRUE);
	// Add a new document
	oDocs = oWord.GetDocuments();
	oDoc = oDocs.Add(vtOptional,vtOptional,vtOptional,vtOptional);

	CreateMailMergeDataFile(&oWord,&oDoc); //this function creates a data file and fills it with the necessary data

         //various formatting//

	// Go to the end of the document
	oSelection.GoTo(COleVariant((short)3), // 3 = wdGoToLine
	COleVariant((short)-1),vtOptional,vtOptional);  // -1 = wdGoToLast

	// Perform mail merge
	oMailMerge.SetDestination(0); // 0 = wdSendToNewDocument
	oMailMerge.Execute(vtFalse);

	// Close the original form document
	oDoc.SetSaved(TRUE);
	oDoc.Close(vtFalse,vtOptional,vtOptional);

oDocs.Save(vtFalse, vtOptional);
oDocs.Close(vtTrue,vtOptional,vtOptional);
Code:
	}
}

I assume that the problem lies in the two lines at the end (in bold). Currently, the program does a "Save-As". I would like it to automatically save to a specific location, then close.

Any help would be appreciated.
 
Hi!

First time when you save a document you should use SaveAs method instead of Save:
Code:
oDocs.SaveAs("C:\\MyDoc\\File1.doc");
First argument is the pathname for new document. All other arguments are optional.

To shut down MS Word you should use Quit method of Application object after you save and close the document:
Code:
Application app;

...

app.Quit();
all arguments of Quit are optional.
Good Luck!

Marius Samoila
Brainbench MVP for Visual C++
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top