Saturday, June 06, 2009

More Word Automation

After figuring out how to add bold text to a Word document from a Delphi program, it was only a short step to figure out how to add underlined text. But the real cherry was finally figuring out how to add bulleted text, ie
  • line one
  • line two
This may appear to be trivial, but the code which Word creates when doing the above as a macro is fairly complicated. I found some code in a Japanese Delphi blog which basically copies the Word macro code and turns it in Delphi, but it didn't work for me. It turns out in the end that most of that code is actually unnecessary, and I managed to write a 'bullet' procedure with only a few lines of code. I am posting the code here in the hope that Google will bookmark it, so when some poor programmer tries to create bulleted text in Delphi, he will have an example which works. Here it is:
procedure wrdBullets (app: variant; const s: string);
{ This procedure MUST be passed the wrdApp object, as ListGalleries is a
property of this object, not of the selection object}
const
 wdBulletGallery = 1;
 wdListApplyToWholeList = 0;
 wdWord10ListBehavior = 2;

var
 template, sel: variant;

begin
 Template:= App.ListGalleries.Item(wdBulletGallery).ListTemplates.Item(1);
 Sel:= App.selection;
 Sel.Range.ListFormat.ApplyListTemplate
(Template, false, wdListApplyToWholeList, wdWord10ListBehavior);

 Sel.typetext (s);
 sel.Range.ListFormat.RemoveNumbers;
end;
As always, the problem with creating Word automation code (in any language, but especially Delphi, which is a non-Microsoft language with a different syntax) is knowing which methods belong to which objects.

I have created a Delphi unit which exports all the more complicated functionality, such as bold, underline, bullet and gotobookmark. This way, I only have to write the complicated code once, and then every program which I write can use this code simply by including a call to a procedure.

Encouraged by these achievements, I also included the unit a procedure which receives a range of Excel cells and puts around and in them a double border.

1 comment:

Unknown said...

Hi,
This was very useful. Is there some information similarly fr table of contents with hyperlinks.