如何查找并替换WORD文本框中的字符?(50分)

  • 主题发起人 主题发起人 codepig
  • 开始时间 开始时间
C

codepig

Unregistered / Unconfirmed
GUEST, unregistred user!
如在word中想把#name 换成 小王,如果#name不是放在文本框中的就可以实现,但是放在文本框中就无法用
wordapplication.document.selection.find.execute来替换了,那位高手可以帮忙?
 
什么意思?
 
在WORD中加一个文本框写入#name,我想把它换成小王如何做?用wordapplication.document.selection.find.execute不行
 
你可以参考下面这段VBA代码
Sub a()
For i = 1 To ActiveDocument.Shapes.Count
ActiveDocument.Shapes(i).Select

Selection.Find.Replacement.ClearFormatting
With Selection.Find
.Text = "#Name"
.Replacement.Text = "小王"
End With
Selection.Find.Execute Replace:=wdReplaceAll
MsgBox i
Next i
End Sub
 
如果不是在文本框中以上的VBA可以做,delphi里我也试过了。你可以做个实验,
写一个WORD文档,在正常的地方写一个#name在文本框中写一个#name用程序替换一下,
你会发现文本框中的#name没有被替换.
 
看看这个对你有无用处?

uses
ComObj;

// Replace Flags
type
TWordReplaceFlags = set of (wrfReplaceAll, wrfMatchCase, wrfMatchWildcards);

function Word_StringReplace(ADocument: TFileName; SearchString, ReplaceString: string; Flags: TWordReplaceFlags): Boolean;
const
wdFindContinue = 1;
wdReplaceOne = 1;
wdReplaceAll = 2;
wdDoNotSaveChanges = 0;
var
WordApp: OLEVariant;
begin
Result := False;

{ Check if file exists }
if not FileExists(ADocument) then
begin
ShowMessage('Specified Document not found.');
Exit;
end;

{ Create the OLE Object }
try
WordApp := CreateOLEObject('Word.Application');
except
on E: Exception do
begin
E.Message := 'Word is not available.';
raise;
end;
end;

try
{ Hide Word }
WordApp.Visible := False;
{ Open the document }
WordApp.Documents.Open(ADocument);
{ Initialize parameters}
WordApp.Selection.Find.ClearFormatting;
WordApp.Selection.Find.Text := SearchString;
WordApp.Selection.Find.Replacement.Text := ReplaceString;
WordApp.Selection.Find.Forward := True;
WordApp.Selection.Find.Wrap := wdFindContinue;
WordApp.Selection.Find.Format := False;
WordApp.Selection.Find.MatchCase := wrfMatchCase in Flags;
WordApp.Selection.Find.MatchWholeWord := False;
WordApp.Selection.Find.MatchWildcards := wrfMatchWildcards in Flags;
WordApp.Selection.Find.MatchSoundsLike := False;
WordApp.Selection.Find.MatchAllWordForms := False;
{ Perform the search}
if wrfReplaceAll in Flags then
WordApp.Selection.Find.Execute(Replace := wdReplaceAll)
else
WordApp.Selection.Find.Execute(Replace := wdReplaceOne);
{ Save word }
WordApp.ActiveDocument.SaveAs(ADocument);
{ Assume that successful }
Result := True;
{ Close the document }
WordApp.ActiveDocument.Close(wdDoNotSaveChanges);
finally
{ Quit Word }
WordApp.Quit;
WordApp := Unassigned;
end;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
Word_StringReplace('C:/Test.doc','Old String','New String',[wrfReplaceAll]);
end;

 
多人接受答案了。
 
后退
顶部