I've a perfectly working function to find and replace a variable with text in word documents.
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, &result, pDocApp, L"Selection", 0);
pSelection=result.pdispVal;
}
IDispatch *pFind;
{
VARIANT result;
VariantInit(&result);
OLEMethod(DISPATCH_PROPERTYGET, &result, 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, &result, pFind, L"Execute", 8, wdContinue, varBoolTrue, varBoolFalse, varBoolFalse, varBoolFalse, 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;
}
The problem is, that this code won't touch any text in the header or the footer.
Maybe there is a parameter for the pFind execute method?
Honestly I've been looking in to this problem since Monday. The most of my search results are VB, C#, .NET and VBA documentation, but there is little documentation on VC++ OLE, a few lines of code, but nothing helpful. I even started to create and translate some Word macros, nothing works.
Here on Stack Overflow I found many questions related to this topic. Some of them looked promising, but it seems they're using some framework I don't know and people have left no response if I asked for sample code or links.
If someone can me help on this matter it'd be awesome and I'd really appreciate links to documentation and code on the general topic of OLE Word automation (besides this codeproject article).
Thanks in advance!