• 0

[C++] MS Word Automation


Question

Have a problem inserting things into predefined places (like mail merge) in a word document.

Here's my code so far:

String AppPath = ExtractFilePath(Application->ExeName);
Variant MSWord;

MSWord = CreateOleObject("Word.Basic");
MSWord.Exec(Procedure("AppShowMSWord.Exec(Procedure("FileOpent;< AppPath+"Word.doc");
MSWord.Exec(Procedure("Insertt;< "Insert Text");

After googling.. i've found InsertAfter as a parameter... but I cant seem to work out how to use it :(

Has anyone done this before?

MdSalih

Link to comment
https://www.neowin.net/forum/topic/287507-c-ms-word-automation/
Share on other sites

4 answers to this question

Recommended Posts

  • 0
  mdsalih said:
*bump * :)

MdSalih

585503286[/snapback]

Sub InsertTextAtEndOfDocument()
    ActiveDocument.Content.InsertAfter Text:=" The end."
End Sub

Sub AddTextBeforeSelection()
    Selection.InsertBefore Text:="new text "
End Sub

From Word's help file:

  Quote
Finding and Replacing Text or Formatting

See AlsoSpecificsFinding and replacing is exposed by the Find and Replacement objects. The Find object is available from the Selection and Range object. The find action differs slightly depending upon whether you access the Find object from the Selection or Range object.

Finding text and selecting it

If the Find object is accessed from the Selection object, the selection is changed when the find criteria is found. The following example selects the next occurrence of the word "Hello." If the end of the document is reached before the word "Hello" is found, the search is stopped.

With Selection.Find

    .Forward = True

    .Wrap = wdFindStop

    .Text = "Hello"

    .Execute

End With

The Find object includes properties that relate to the options in the Find and Replace dialog box (choose Find from the Edit menu). You can set the individual properties of the Find object or use arguments with the Execute method as shown in the following example.

Selection.Find.Execute FindText:="Hello", _

    Forward:=True, Wrap:=wdFindStop

Finding text without changing the selection

If the Find object is accessed from a Range object, the selection is not changed but the Range is redefined when the find criteria is found. The following example locates the first occurrence of the word "blue" in the active document. If the find operation is successful, the range is redefined and bold formatting is applied to the word "blue."

With ActiveDocument.Content.Find

    .Text = "blue"

    .Forward = True

    .Execute

    If .Found = True Then .Parent.Bold = True

End With

The following example performs the same result as the previous example using arguments of the Execute method.

Set myRange = ActiveDocument.Content

myRange.Find.Execute FindText:="blue", Forward:=True

If myRange.Find.Found = True Then myRange.Bold = True

Using the Replacement object

The Replacement object represents the replace criteria for a find and replace operation. The properties and methods of the Replacement object correspond to the options in the Find and Replace dialog box (Edit menu).

The Replacement object is available from the Find object. The following example replaces all occurrences of the word "hi" with "hello." The selection changes when the find criteria is found because the Find object is accessed from the Selection object.

With Selection.Find

    .ClearFormatting

    .Text = "hi"

    .Replacement.ClearFormatting

    .Replacement.Text = "hello"

    .Execute Replace:=wdReplaceAll, Forward:=True, _

        Wrap:=wdFindContinue

End With

The following example removes bold formatting in the active document. The Bold property is True for the Find object and False for the Replacement object. In order to find and replace formatting, set the find and replace text to empty strings ("") and set the Format argument of the Execute method to True. The selection remains unchanged because the Find object is accessed from a Range object (the Content property returns a Range object).

With ActiveDocument.Content.Find

    .ClearFormatting

    .Font.Bold = True

    With .Replacement

        .ClearFormatting

        .Font.Bold = False

    End With

    .Execute FindText:="", ReplaceWith:="", _

        Format:=True, Replace:=wdReplaceAll

End With

  • 0
  mdsalih said:
Thank You :)

Now I've got to work out how to do it in Borland C++ Builder :-/

MdSalih

585511955[/snapback]

It's been so long since I've used BCB, but I think you can import an ActiveX/COM dll which BCB will wrap with VCL. I seem to recall doing something to that effect with MSXML.

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • It's become a central place at my workplace. I use it for meetings, general chatting between employees, and the teams for storing of files to share between people at work. 
    • It's a Dell color laser printer. Back when Microsoft kept having these security flaws with the print spooler and recommending you disable it I just got in the habit of it, and I use it so rarely now I just leave it disabled in case another flaw pops up.
    • KDE makes progress toward full Wayland session restore in Plasma 6.5 by David Uzondu In the latest issue of This Week in Plasma, the development team, as usual, brings news of ongoing work for the desktop environment. While KDE continues to polish the recently released Plasma 6.4, work has already taken off on the next major version of Plasma, 6.5. A significant step forward is being made on Wayland session restoration; the xx-session-management-v1 restore protocol has been implemented in Qt 6.10, which means KDE applications and Plasma itself can soon start using it to finally bring proper session restore to Wayland. For more immediate user-facing changes in Plasma 6.5, the Welcome Center application now teaches you about the many available keyboard shortcuts, as well as "what the heck the 'Meta' key is." For those who frequently work remotely, Plasma's built-in RDP server now supports syncing clipboard text between the client and server. The clipboard also received another useful feature, letting you copy the QR code for an item, not just view it. The team is also addressing smaller usability issues across the desktop, including fixes that will land in point releases for Plasma 6.4. Spectacle, for example, will no longer show a ghostly semi-transparent version of its menus in screenshots. The New! badge, which was introduced in Plasma 6.4 is now easier to read with better colors. Other notable UI improvements include: A new button on the "missed notifications" pop-up that lets you view what you actually missed. The Networks widget is now much better at telling you what it is doing, like when it is "looking for wireless networks". Inertial scrolling with touchpads is now active in all QtQuick-based KDE software. As always, the KDE team spent the week squashing bugs across various versions of Plasma and related software. Plasma 6.4.1, which went live this Tuesday, addressed several crashes in the desktop portal implementations and patched the open/save dialog, where apps could insert extra UI elements in the wrong places. It also resolved a recent performance regression affecting some games and fixed a strange issue with drawing tablets where the pointer could disappear when two were connected in different modes. 6.4.1 tackled a particularly odd hardware-specific problem with Samsung Odyssey G5 monitors endlessly turning on and off because of a faulty DDC implementation. KDE responded by blacklisting the device. In addition to that, the update fixed an accessibility regression in Discover, corrected an issue where deleting a favorited app left behind a ghost item you couldn't un-favorite, and restored the Window List widget's ability to minimize windows. As for fixes planned for 6.4.2, here's the full list as outlined by the Plasma team: Fixed a case where System Settings' Flatpak App Permissions page could cause the whole app to crash. Fixed an issue that could sometimes cause Plasma to go back to sleep again right after waking up, when the "Sleep then hibernate" setting is in use. The appearance of text labels in Folder View pop-ups is once again correct. You're no longer erroneously prompted to authenticate for a Wireguard VPN whose credentials are already stored in KWallet, and the wallet is set up to automatically open at login. Fixed an issue in the KDE desktop portal's screenshot implementation that prevented the delay setting from taking effect. Missing app backends listed in Discover's Settings page once again show the correct names. The brightness level shown on System Settings' Display & Monitor page now matches the one shown in Plasma. Fixed an issue that caused the panel to have too much space in it until restarting Plasma if you stop displaying the date on a horizontally-laid-out Digital Clock widget. The older Plasma 6.3.6 fixed video stuttering on variable-refresh-rate screens and patched the Weather Report widget after Environment Canada changed its data format. You can check out the full update on the official KDE Blog.
    • I'm happy with my setup. I have a raid 1 two drive Synology setup that I backup with Time Machine to every so often. What is your setup at home? 
    • Enterprise support (ex. Premier Support) is a bit different cup of coffee. I am not saying it is great, but they have SLAs and I have received solution within hours and even patches within 3 days.
  • Recent Achievements

    • One Year In
      TsunadeMama earned a badge
      One Year In
    • Week One Done
      shaheen earned a badge
      Week One Done
    • Dedicated
      Cole Multipass earned a badge
      Dedicated
    • Week One Done
      Alexander 001 earned a badge
      Week One Done
    • Week One Done
      icecreamconesleeves earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      569
    2. 2
      ATLien_0
      187
    3. 3
      +FloatingFatMan
      184
    4. 4
      Skyfrog
      112
    5. 5
      Som
      108
  • Tell a friend

    Love Neowin? Tell a friend!