i have the following function, which should return the position of the first occurrence of the text i'm searching for. The problem:
- returns -1
- throws AV-s, when i'm using the whole document content as a range (or using a range with the boundaries of the document content)
What have i done:
- Lots of Google searches, to find the source of the problem, or alternatives to this code
- MSDN digging
- Trial and error
Here is the code:
function FindTextWord(wordApp: TWordApplication; afindText: OleVariant; startIndex, endIndex: Integer; findEndOffsetFast: Boolean): Integer;
var
matchCase : OleVariant;
matchWholeWord : OleVariant;
matchWildcards : OleVariant;
matchSoundsLike : OleVariant;
matchAllWordForms: OleVariant;
fWd : OleVariant;
wrap : OleVariant;
format : OleVariant;
replaceWith : OleVariant;
replace : OleVariant;
myRange : Range;
startSearchOffset: OleVariant;
endSearchOffset : OleVariant;
begin
WordApp.Selection.Start := 0;
WordApp.Selection.End_ := 0;
result:=-1;
try
if (Assigned(WordApp)) then
begin
if (startIndex<1) then
begin
WordApp.ActiveDocument.GrammarChecked:=true;
WordApp.ActiveDocument.SpellingChecked:=true;
WordApp.ActiveDocument.ShowGrammaticalErrors:=false;
WordApp.ActiveDocument.ShowSpellingErrors:=false;
startSearchOffset:=WordApp.ActiveDocument.Content.Start;
end else
begin
startSearchOffset:=startIndex;
end;
if (endIndex<1) then
begin
if (findEndOffsetFast)or(startIndex<1) then
begin
endSearchOffset:=WordApp.ActiveDocument.Content.End_;
end else
begin
endSearchOffset:=startSearchOffset+1;
WordApp.Selection.Start:=startSearchOffset;
while (WordApp.Selection.Start=startSearchOffset)and(endSearchOffset<WordApp.ActiveDocument.Content.End_)and(endSearchOffset-startSearchOffset<4000) do
begin
endSearchOffset:=endSearchOffset+1;
WordApp.Selection.End_:=endSearchOffset;
end;
endSearchOffset:=endSearchOffset-1-Length(afindText);
end;
end else
begin
endSearchOffset:=endIndex;
end;
myRange:=WordApp.ActiveDocument.Range(startSearchOffset,endSearchOffset);
myRange.Find.ClearFormatting;
myRange.Start:=Integer(startSearchOffset);
myRange.End_:=Integer(endSearchOffset);
MatchCase := False;
MatchWholeWord := TRUE;
MatchWildcards := False;
MatchSoundsLike := False;
MatchAllWordForms := False;
fWd := True;
Wrap := wdFindStop;
Format := False;
ReplaceWith := '';
Replace := wdReplaceNone;
if MyRange.Find.Execute(aFindText,MatchCase,MatchWholeWord,
MatchWildcards,MatchSoundsLike,
MatchAllWordForms,fWd,
Wrap,Format,ReplaceWith,Replace)
then begin
if (myRange.Start>=startSearchOffset) then
begin
if (myRange.Find.Found) then
begin
result:=myRange.Start;
end;
end else
begin
result:=FindTextWord(wordApp,afindText,startIndex,endIndex,false);
end;
end;
end;
except
end;
end;
Update
The problem is not replacing text (i must remove all HTML tags which may appear in the word document, but with the following twist: if i encounter formatting tags, such as b, i, u, s, strong, and the like, i have to remove them and format the text accordingly)