change text in microsoft word programatically

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • BlackMustard
    New Member
    • Aug 2007
    • 88

    #1

    change text in microsoft word programatically

    hi

    i would like to open a document template (saved as a regular .doc), replace a couple of instances of "XXXX" with a user-specified number. i imported the library "microsoft word 11.0 object library" and tried playing around a little with the syntax help in vb6, but didn't find anything helpful.

    is there an easy way to open a document, run a replace function, save it with a new file name and close all open documents programatically ?

    br / bm
  • kadghar
    Recognized Expert Top Contributor
    • Apr 2007
    • 1302

    #2
    I think thats possible.

    First of all, it would be nice to know what version of VB you're using, since the VBA of word could make things way easier than VB6.

    Then in the while, why dont you read a little bit about some sintaxis like Selection, Find, Replacement syntaxis, just google them.

    Comment

    • QVeen72
      Recognized Expert Top Contributor
      • Oct 2006
      • 1445

      #3
      Hi,

      Check this :

      [code=vb]
      '
      Selection.Whole Story
      Selection.Find. ClearFormatting
      Selection.Find. Replacement.Cle arFormatting
      With Selection.Find
      .Text = "Old"
      .Replacement.Te xt = "New"
      .Forward = True
      .Wrap = wdFindAsk
      .Format = False
      .MatchCase = False
      .MatchWholeWord = False
      .MatchWildcards = False
      .MatchSoundsLik e = False
      .MatchAllWordFo rms = False
      End With
      Selection.Find. Execute Replace:=wdRepl aceAll
      ActiveDocument. Save
      [/code]

      REgards
      Veena

      Comment

      • kadghar
        Recognized Expert Top Contributor
        • Apr 2007
        • 1302

        #4
        Originally posted by QVeen72
        Hi,

        Check this :

        [code=vb]
        '
        Selection.Whole Story
        Selection.Find. ClearFormatting
        Selection.Find. Replacement.Cle arFormatting
        With Selection.Find
        .Text = "Old"
        .Replacement.Te xt = "New"
        .Forward = True
        .Wrap = wdFindAsk
        .Format = False
        .MatchCase = False
        .MatchWholeWord = False
        .MatchWildcards = False
        .MatchSoundsLik e = False
        .MatchAllWordFo rms = False
        End With
        Selection.Find. Execute Replace:=wdRepl aceAll
        ActiveDocument. Save
        [/code]

        REgards
        Veena
        That will work for VBA in Word, remember that when you record a macro, it uses as many constants as posible. If you use VBA in PowerPoint, for example. and you create an object with a Word Application in it, it wont recognize "wdReplaceA ll" since its a Word constant that PowerPoint's VBA dont know.

        That's why its important to know which version of VB we are using.

        Comment

        • QVeen72
          Recognized Expert Top Contributor
          • Oct 2006
          • 1445

          #5
          Originally posted by kadghar
          That will work for VBA in Word, remember that when you record a macro, it uses as many constants as posible. If you use VBA in PowerPoint, for example. and you create an object with a Word Application in it, it wont recognize "wdReplaceA ll" since its a Word constant that PowerPoint's VBA dont know.

          That's why its important to know which version of VB we are using.

          Hi,

          The Question was to Replace in "Word" na, I dont think he wanted for PowerPoint...

          Regards
          Veena

          Comment

          • kadghar
            Recognized Expert Top Contributor
            • Apr 2007
            • 1302

            #6
            Ok anyway, since he was playing around with some VB6 sintax....

            Anyway, for Word, may be this will be of help:

            [CODE=vb]Sub ReplaceTxt()
            Dim Str1 As String
            Dim Int1 As Integer
            With Application.Fil eDialog(3)
            .Filters.Clear
            .Filters.Add "Word File (*.doc)", "*.doc"
            .Filters.Add "All Files (*.*)", "*.*"
            .Show
            If .SelectedItems. Count > 0 Then
            Str1 = .SelectedItems( 1)
            Else
            Exit Sub
            End If
            End With
            Documents.Open (Str1)
            Int1 = Documents.Count
            Documents(Int1) .Activate
            With Selection.Find
            .Text = InputBox("Text to be replaced", "Replacemen t", "")
            .Replacement.Te xt = InputBox("With" , "Replacemen t", "")
            .Wrap = 1
            .Execute Replace:=2
            End With
            Documents(Int1) .Close savechanges:=Tr ue
            If MsgBox("Check another Document?", 4) = 6 Then Call ReplaceTxt
            End Sub[/CODE]

            Comment

            • BlackMustard
              New Member
              • Aug 2007
              • 88

              #7
              i actually want to do it in a macro written in the macro editor in outlook (the one you open by pressing alt+f11 while outlook is focused), so all of your guesses were wrong =). i just assumed this editor was using vb6, but i might be wrong...? my main focus has been asp and asp.net for a long time, even though my programming career started with vb6 at age 12 =). i guess a lot has happened since...

              to be more specific with what i need:

              in my job i often use a standardized word document to give information to our customers. every time i send one of these, i need to open the standard doc, replace three instances of XXXX with a four digit issue number, close it and attach it to the email.
              attaching it to the email is not that big of a deal, but this open word - do a couple of things - save as - close word takes a lot of unecessary time, so i hoped i would be able to do that by just pressing a button directly in outlook.

              Comment

              • Martin2007
                New Member
                • Jul 2007
                • 21

                #8
                Originally posted by BlackMustard
                i actually want to do it in a macro written in the macro editor in outlook (the one you open by pressing alt+f11 while outlook is focused), so all of your guesses were wrong =). i just assumed this editor was using vb6, but i might be wrong...? my main focus has been asp and asp.net for a long time, even though my programming career started with vb6 at age 12 =). i guess a lot has happened since...

                to be more specific with what i need:

                in my job i often use a standardized word document to give information to our customers. every time i send one of these, i need to open the standard doc, replace three instances of XXXX with a four digit issue number, close it and attach it to the email.
                attaching it to the email is not that big of a deal, but this open word - do a couple of things - save as - close word takes a lot of unecessary time, so i hoped i would be able to do that by just pressing a button directly in outlook.
                Just had a really quick look at Outlook, you can create a custom tool bar, then using vb, design yourself a nice window, with a replace "something" textbox with "something else" text box... behind that form you could then put all the code mentioned above... then add a button to the custom menu to launch your new form...

                Just thinking outloud, I wouldnt know how to do this, but just looking quickly into it I think it could be a way forward?


                Edit: Yeah, 5 min of poking around, you can add a custom toolbar, then add a button onto that toolbar that will open up a custom form, from there you should be able to do anything you want as long as the commands are supported by Outlook VBA...

                Literally create a new form in the VB editor, make that form do what you want it to do and then add it as a button...

                Hope this helps!

                Martin

                Comment

                • kadghar
                  Recognized Expert Top Contributor
                  • Apr 2007
                  • 1302

                  #9
                  Originally posted by BlackMustard
                  i actually want to do it in a macro written in the macro editor in outlook (the one you open by pressing alt+f11 while outlook is focused), so all of your guesses were wrong =). i just assumed this editor was using vb6, but i might be wrong...? my main focus has been asp and asp.net for a long time, even though my programming career started with vb6 at age 12 =). i guess a lot has happened since...

                  to be more specific with what i need:

                  in my job i often use a standardized word document to give information to our customers. every time i send one of these, i need to open the standard doc, replace three instances of XXXX with a four digit issue number, close it and attach it to the email.
                  attaching it to the email is not that big of a deal, but this open word - do a couple of things - save as - close word takes a lot of unecessary time, so i hoped i would be able to do that by just pressing a button directly in outlook.
                  Of course its posible, just create an object with a Word Application in it and work with it :) the code i put above. Should be something like this:

                  [CODE=vb]Sub Replacing()
                  Dim Obj1 As Object
                  Dim Str1 As String
                  Dim Int1 As Integer
                  Set Obj1 = CreateObject("w ord.application ")
                  With Obj1.FileDialog (3)
                  .Filters.Clear
                  .Filters.Add "Word File (*.doc)", "*.doc"
                  .Filters.Add "All Files (*.*)", "*.*"
                  .Show
                  If .SelectedItems. Count > 0 Then
                  Str1 = .SelectedItems( 1)
                  Else
                  Exit Sub
                  End If
                  End With
                  Obj1.Documents. Open (Str1)
                  Obj1.Visible = False
                  With Obj1.Selection. Find
                  .Text = InputBox("Text to be replaced", "Replacemen t", "")
                  .Replacement.Te xt = InputBox("With" , "Replacemen t", "")
                  .Wrap = 1
                  .Execute Replace:=2
                  End With
                  Obj1.Visible = True
                  Obj1.Documents( 1).Close savechanges:=Tr ue
                  Obj1.Quit
                  If MsgBox("Check another Document?", 4) = 6 Then Call Replacing
                  End Sub[/CODE]

                  Comment

                  • kadghar
                    Recognized Expert Top Contributor
                    • Apr 2007
                    • 1302

                    #10
                    oh, please note that i had to use the FileDialogs of the Word Application, because the VBA of Outlook doesnt support them (dunno why)

                    Comment

                    • BlackMustard
                      New Member
                      • Aug 2007
                      • 88

                      #11
                      i actually wanted everything to work without the open file dialog, or any other on-screen action. here's a sub i found worked pretty well:

                      [CODE=vb]Sub CreateRMADoc()
                      Dim appWord As New Word.Applicatio n

                      Dim intRMA, i As Integer
                      Dim strDate, strFileName As String
                      Dim Range As Range

                      'Define the path where to save the RMA.doc
                      intRMA = InputBox("RMA Number:", "Create RMA Document", "")
                      strDate = Format(Now(), "yyyy-mm-dd")
                      strFileName = "CAR " & intRMA & " Repair and RMA Instruction Ericsson.doc"

                      'Open the RMA Word Template
                      appWord.Documen ts.Open ("C:\Documen ts and Settings\qtomly c\My Documents\Attac hments\TEMPLATE Repair and RMA Instruction Ericsson.doc")

                      ' Make Word invisible through the Application object.
                      appWord.Visible = False

                      'Change date in document
                      For i = 1 To 15
                      Set Range = appWord.ActiveD ocument.Content
                      Range.Find.Exec ute FindText:="2007-XX-XX", ReplaceWith:=st rDate
                      Next i

                      'Change reference of RMA in document
                      For i = 1 To 15
                      Set Range = appWord.ActiveD ocument.Content
                      Range.Find.Exec ute FindText:="XXXX ", ReplaceWith:=in tRMA
                      Next i

                      ' Save the new RMA document
                      appWord.ActiveD ocument.SaveAs "C:\Documen ts and Settings\qtomly c\My Documents\Attac hments\CAR " & intRMA & " Repair and RMA Instruction Ericsson.doc"


                      ' Dispose objects to free memory
                      appWord.ActiveD ocument.Close
                      Set appWord = Nothing
                      Set Range = Nothing
                      End Sub[/CODE]

                      but i'm experiencing two problems:

                      1. it doesn't change anything in headers and footers, which i need it to. how do i access the header in the same manner as appWord.ActiveD ocument.Content gives me all the content of the document? if possible, i would like to to this also with some text in a text box. however, i found a work-around to the later of the two by making a bitmap that looks like a textbox, and place it behind the text.

                      2. it seems that i'm not closing the files completely - the second time i run the macro i get a file sharing violation or something of that nature on the saveas line, stating that the file is already in use by another program. what can i do to close the file so that i can open and save again, without having to find the program still using the file, close it and then resume the macro?

                      Comment

                      • BlackMustard
                        New Member
                        • Aug 2007
                        • 88

                        #12
                        ok, i know double posting is probably not allowed, but i need help with this and i don't expect people to be looking at threads on page 4, so i'm bumping...

                        ...anyone knows a solution to any of the problems stated above?

                        Comment

                        Working...