Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

How to Replace a text in MS Word using Delphi

Posted on 1999-07-13
16
Medium Priority
?
705 Views
Last Modified: 2010-04-06
Hi,

I'm making a program which must merge a MS Word doc file with a database fields.
I already know how to create new doc file and how to insert a text in it  from Delphi 4, but I need to know if there is a possibility to replace a text in an existing doc file.

For example <Name> must be replaced with 'Peter Johnson'
<Address> with 'Santa Monica blv'
and so on.

Thank you in advance
Roumen


0
Comment
Question by:rumpet
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 3
  • 2
  • +5
16 Comments
 
LVL 13

Expert Comment

by:Epsylon
ID: 1388239
Are you using Outlook for names, addresses etc?

Here is some info on Outlook and Word:

http://www.progfa.com/delphi/faq/uddf/pages/msoffice.htm
0
 
LVL 3

Expert Comment

by:Pegasus100397
ID: 1388240
Rumpet,

I'm assuming that the doc may be large and that your program will step through it line-by-line correct? If so read each line and pass it to the following function:

=========================================================
{ This function searches for the occurance of a substring
  (sToReplace) within another string (sOrg) and replaces
  it with (sReplaceWith).        The result is the
  origional string with the replacements made. If no
  replacements were made then the origional string is
  returned without modification.
}

function fnStrReplace(sOrg: String;
         sToReplace: String; sReplaceWith: String): String;
var kxIDX: Integer;
Begin
kxIDX := 0;
While Pos(sToReplace, sOrg) >kxIDX do
      Begin
      kxIDX := Pos(sToReplace,sOrg);
      Delete(sOrg,kxIDX,Length(sToReplace));
      Insert(sReplaceWith, sOrg, kxIDX);
      end;
Result := sOrg;
end;
=========================================================
An example would be

//Open file...
//read a line into "sLineString"

sLineString := fnStrReplace(sLineString, '<Name>', 'Peter Johnson')

Then write it back out to a secondary (temp) file, print it, whatever and when your done with all the lines in the document, print the temp file, dump it and do it all over again with the next name, address, etc.

Hope this helps and Good Luck with your project!

Pegasus
0
 

Author Comment

by:rumpet
ID: 1388241
Thank you Pegasus,
but if it was so easy to do it in this way I would have already done it.
The problem is that the doc file may have background color, pictures, text which is bold and so on.
If I simpy replace the lines and make a new doc file I'll lose the rest information
( pictures etc. )
I speak about  OLE automation, using the find & replace function of
Word. I think that the answer is in the VBA docs for Word, but I haven't got them.

I think that it is more clear now.
Thanks,
Roumen
 
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 3

Expert Comment

by:Pegasus100397
ID: 1388242
Rumpet,

Understood. Your origional question did not reflect these things. Good luck with your project.

Pegasus
0
 

Expert Comment

by:GabeinOZ
ID: 1388243
Are you trying to make a quasi newsletter writing and distribution program? If so its much easier to forget the word ole and just send your form to a browser and find/replace your text there and then print it.......if printing is your ultimate goal here which I assume it is due to the references to address.

Gabe
0
 
LVL 2

Expert Comment

by:kotik
ID: 1388244
Hi, rumpet!
If you use Word 97 you can do anything you want.
You can get the procedures and functions by recording a macros and then opening the Visual Basic editor in Word you will get all your operations.
You can use the same functions in Delphi, f. e.:
...
  Word.Selection.MoveRight;
  Word.TypeText('Peter Johnson');
...

if you get questions with recording macros I'll help you.
And what's the main problem: to find the text or to replace it?
0
 
LVL 6

Expert Comment

by:Stuart_Johnson
ID: 1388245
VBA is definately the answer here.  Word, unfortunately, does something to its files which does not allow them to be editted without corrupting them, therefore you need to edit them directly using a method which will write the Word format back to disk.

There used to be a program which was available _AGES_ ago for Delphi 1 which used Word documents for templates, but I can not for the life of me remember what it was (anyone?).

Short of that, Automation will do it, but it wouldnt be a job I would like to tackle at this stage.

Just as food for thought, I have written quite a few mail-merge applications, and the way I define a replacement field is to use some marker characters.  For instance, if I wanted to scan a document and replace a field with a name of someone, I would mark the replacement area in the original file like this <%@FIRSTNAME@%>.  The likelyhood of this exact string being inserted into a document is so unlikely, I doubt it would ever happen.

Sorry I cant help you any more than this at the moment.  It looks like a very interesting project!!

Stu.
0
 
LVL 7

Accepted Solution

by:
RBertora earned 1200 total points
ID: 1388246
Here is your answer:

uses comobj;

procedure TForm1.Button1Click(Sender: TObject);
begin
  WordApp := CreateOleObject('Word.Application');
  WordApp.Visible := True;
  WordApp.Documents.Open('c:\demo.doc');
end;

procedure TForm1.Button2Click(Sender: TObject);
begin
  WordApp.Selection.Find.ClearFormatting;
  WordApp.Selection.Find.Replacement.ClearFormatting;
  WordApp.Selection.Find.Execute('Hi',True,False,False,False,False,True,1,False,'Hello',2);
(* expression.Execute(FindText,MatchCase,MatchWholeWord,MatchWildcards,MatchSoundsLike,
    MatchAllWordForms,Forward,Wrap,Format,ReplaceWith,Replace) *)
end;


procedure TForm1.Button3Click(Sender: TObject);
begin
  WordApp.Quit;
end;

0
 
LVL 1

Expert Comment

by:yk030299
ID: 1388247
I knew there are some function to merge document with database::MergePrint.
does it help?
0
 
LVL 6

Expert Comment

by:Stuart_Johnson
ID: 1388248
RBertora has hit the nail right on the head!

RBertora.  Where do you find info like this?  Any books you can recommend to us all?

Cheers,

Stu.
0
 
LVL 7

Expert Comment

by:RBertora
ID: 1388249
Um, I don't know of any books, I use VBAWRD8.hlp, which ships with standard version of office 98.

With a bit of determination one can figure out the Delphi equivalent of the VB code in this file. Start with the
Application object and work from there.

Regards,
Bert.
0
 
LVL 6

Expert Comment

by:Stuart_Johnson
ID: 1388250
Thanks for the tip, Bert.  I'll definately take a look!

Stu.
0
 
LVL 7

Expert Comment

by:RBertora
ID: 1388251
Cool its fairly powerfull stuff, but a bit slow, with com though you can interface to word (not 98 but 2000 I think)
in a more direct manner which should be a lot faster than the ole/variant method.. unfortunately I do not have the newest version of word, and cannot test the theory... any way this does fairly well for the moment.
hope rumpet finds it worth A grade, and you suceed with your stuff Stuart.
0
 
LVL 2

Expert Comment

by:kotik
ID: 1388252
Hi, Stu!
Another tip:
In Word 97 press Alt+F11 - it will open Visual Basic Editor,
after that press F2 - and you will get all classes and functions.

0
 
LVL 6

Expert Comment

by:Stuart_Johnson
ID: 1388253
This is fantastic!  Thanks heaps for this guys.  Although it is something that I have not really needed to do a lot of in the past, its definately something I will have to remember in the future!

Thanks again.

Stu.
0
 

Author Comment

by:rumpet
ID: 1388254
Thank you !!!
Thank you !!!
Thank you RBertora !!!
It's EXACTLY what I'm looking for.
And It WORKS.
You deserve your points.
Now I can finish my project.

Thanks again,
Roumen
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

A lot of questions regard threads in Delphi.   One of the more specific questions is how to show progress of the thread.   Updating a progressbar from inside a thread is a mistake. A solution to this would be to send a synchronized message to the…
This article explains how to create forms/units independent of other forms/units object names in a delphi project. Have you ever created a form for user input in a Delphi project and then had the need to have that same form in a other Delphi proj…
In this video you will find out how to export Office 365 mailboxes using the built in eDiscovery tool. Bear in mind that although this method might be useful in some cases, using PST files as Office 365 backup is troublesome in a long run (more on t…
In response to a need for security and privacy, and to continue fostering an environment members can turn to for support, solutions, and education, Experts Exchange has created anonymous question capabilities. This new feature is available to our Pr…
Suggested Courses

715 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question