我有一个完美的工作功能来查找和替换一个变量与文本中的文本.
HRESULT CMSWord::FindReplace( CString szVar,CString szText,bool bOnlyOnce/*=false*/ )
{
if(m_pWApp==NULL || m_pActiveDocument==NULL) return E_FAIL;
Idispatch *pDocApp;
{
VARIANT result;
Variantinit(&result);
OLEMethod(disPATCH_PROPERTYGET,&result,m_pActiveDocument,L"Application",0);
pDocApp= result.pdispVal;
}
Idispatch *pSelection;
{
VARIANT result;
Variantinit(&result);
OLEMethod(disPATCH_PROPERTYGET,pDocApp,L"Selection",0);
pSelection=result.pdispVal;
}
Idispatch *pFind;
{
VARIANT result;
Variantinit(&result);
OLEMethod(disPATCH_PROPERTYGET,pSelection,L"Find",0);
pFind=result.pdispVal;
}
OLEMethod(disPATCH_METHOD,NULL,pFind,L"ClearFormatting",0);
szText.Replace(_T("\r\n"),_T("\v"));
COleVariant sVariable(szVar);
COleVariant sReplaceText(szText);
COleVariant replace((long)2);
COleVariant varBoolTrue;
varBoolTrue.boolVal = true;
COleVariant varBoolFalse;
varBoolFalse.boolVal = false;
COleVariant wdContinue((long)1);
bool bFound=false;
Idispatch *pExecute = NULL;
{
for(;;) {
VARIANT result;
Variantinit(&result);
if(OLEMethod(disPATCH_METHOD,L"Execute",8,wdContinue,varBoolTrue,varBoolFalse,sVariable)==S_OK) {
pExecute=result.pdispVal;
if(!pExecute) break;
bFound = true;
if(szText.IsEmpty()) DeleteChar(false); else SetSelectionText(szText);
}
else break;
if(bOnlyOnce) break;
}
}
pDocApp->Release();
pSelection->Release();
pFind->Release();
if(!bFound) return E_FAIL;
else return S_OK;
}
问题是,该代码不会触及标题或页脚中的任何文本.
也许pFind的执行方法有一个参数?
老实说,星期一我一直在寻找这个问题.我的大部分搜索结果是VB,C#,.NET和VBA文档,但是没有关于VC OLE的文档,几行代码,但没有任何帮助.我甚至开始创建和翻译一些Word宏,没有任何作用.
堆栈溢出这里我发现了许多与此主题有关的问题.有些人看起来很有希望,但似乎他们正在使用一些我不知道的框架,如果我要求示例代码或链接,人们没有回复.
如果有人可以帮助我解决这个问题,那将是非常棒的,我非常喜欢链接文档和OLE Word自动化的一般主题的代码(除了这个代码项目的文章).
提前致谢!
解决方法
这是一个Delphi函数,在标题中进行搜索和替换.我知道这是一个C问题,但您可以从功能中看到您需要做什么.
我总是发现,在工作中做最简单的方法是使用MacroRecorder并查看文字,然后从应用程序中调用该代码.
很可惜你在C中做COM编程
Procedure Find_ReplaceText(find,ReplaceWith: String; Header : Boolean = false);
var
tmpText: String;
spos,epos : Integer;
begin
{Start on first page.}
fWordApp.Selection.Goto(wdGoToPage,wdGotoFirst);
{Extra code is needed if I'm trying to replace text in the header}
if Header then
begin
fWordApp.ActiveWindow.ActivePane.View.SeekView := wdSeekCurrentPageHeader;
If fWordApp.Selection.headerfooter.IsHeader = False Then
begin
fWordApp.ActiveWindow.ActivePane.View.SeekView := wdSeekCurrentPageHeader;
end;
tmpText := fWordApp.ActiveDocument.sections.item(1).Headers.item(wdheaderfooterPrimary).Range.text;
spos := pos('[',tmptext);
epos := pos(']',tmpText);
tmptext := copy(tmptext,1,spos);
tmptext := tmptext + ReplaceWith + ']';
fWordApp.ActiveDocument.sections.item(1).Headers.item(wdheaderfooterPrimary).Range.text := tmptext;
fWordApp.ActiveWindow.ActivePane.View.SeekView := wdSeekMainDocument;
end
else
begin
fWordApp.Selection.Find.Text := find;
fWordApp.Selection.Find.Execute;
fWordApp.Selection.typeText(' ');
fWordApp.Selection.InsertAfter(ReplaceWith);
end;
end;