发信人: galfordli()
整理人: wenbobo(2002-12-27 15:51:54), 站内信件
|
下面的函数演示了如何从VC中调用WORD接口,功能很简单,县新建了一个新文件 ,然后对文件中的字符作替换。
要运行下面的代码,先要从MSWORD8.OLB中加入所需的类,然后就可以想些什么就 干什么了,每个类中的成员函数都是和VBA中的对应的,可以现在WORD中录制一个 宏,然后照着试试。
void CWord1Dlg::OnOK()
{
_Application myApp;
Documents myDocs;
_Document myDoc;
Range myRange;
Find fndInDoc;
Replacement rpInDoc;
//产生WORD的对象
if(!myApp.CreateDispatch("Word.Application"))
{
TRACE("\nmyWord.CreateDispatch failed!!");
return;
}
myDocs=myApp.GetDocuments();
myDoc=myDocs.Open(COleVariant("c:\\test.doc"));
myRange=myDoc.GetContent();
fndInDoc=myRange.GetFind();
fndInDoc.ClearFormatting();
rpInDoc=fndInDoc.GetReplacement();
rpInDoc.ClearFormatting();
short wdReplaceAll=2;
short wdFindAsk=2;
short wdFindContinue=1;
BOOL bF=false;
BOOL bT=true;
COleVariant vFalse((short)FALSE),
vOpt((long)DISP_E_PARAMNOTFOUND, VT_ERROR);
/*fndInDoc.Execute(&COleVariant("国际"),&COleVariant((short)bF),
&COleVariant((short)bF),&COleVariant((short)bF),
&COleVariant((short)bF),&COleVariant((short)bF),
&COleVariant((short)bT),&COleVariant(wdFindAsk),
&COleVariant((short)bF),&COleVariant("Galford"),
&COleVariant(wdReplaceAll));*/
//这两句的功能是一样的,可以差异下Word VBA,
//如果有表明参数可选,就可以用vOpt代替
fndInDoc.Execute(&COleVariant("国际"),vOpt,vOpt,vOpt,vOpt,
vOpt,vOpt,vOpt,vOpt,&COleVariant("Galford"),
&COleVariant(wdReplaceAll));
myDoc.Save();
AfxMessageBox("OK");
myApp.Quit(vFalse, vOpt, vOpt);
myApp.ReleaseDispatch();
//CDialog::OnOK();
}
void CWord1Dlg::OnButton1()
{
_Application myApp;
Documents myDocs;
_Document myDoc;
COleVariant vOpt(DISP_E_PARAMNOTFOUND, VT_ERROR);
if(!myApp.CreateDispatch("Word.Application", NULL))
{
TRACE("\nmyWord.CreateDispatch failed!!");
return;
}
myDocs = myApp.GetDocuments();
myDoc = myDocs.Add(vOpt, vOpt);
Range myRange= myDoc.Range(vOpt,vOpt);
myRange.SetText("国际标准化组织");
myDoc.SaveAs(COleVariant("C:\\test.doc"),vOpt,vOpt,vOpt,vOpt,vOpt,vOpt ,vOpt,vOpt,vOpt,vOpt);
myDoc.Close(COleVariant((short)false), vOpt, vOpt);
AfxMessageBox("OK");
myDoc.ReleaseDispatch();
myDoc.m_lpDispatch = NULL;
}
-- ※ 来源:.月光软件站 http://www.moon-soft.com.[FROM: 202.99.79.191]
|
|