简体   繁体   中英

How to trigger the find replace sequence in a Word document using Excel VBA?

I am looking for a way to:

  1. Open Word document based on cell XX in Excel sheet (right now, I list the full pathway of the document in cell XX. Is there a way I can open a document based on an identifier in the Word doc's filename?)
  2. Edit text in Word document using find and replace (links between Excel and Word doc, I am updating the pathway for these links. Old pathway is static, new pathway changes depending on user and will be found in cell XXX)
  3. Trigger update of all links in word after find replace
  4. Break those links
  5. Rename and save word document in client folder
Sub openfile()
    'opening word file based on cell value in excel, this part works
    Dim File As String

    File = Worksheets("HOME").Range("A54").Value
    Set wordapp = CreateObject("word.Application")
    wordapp.documents.Open File
    wordapp.Visible = True
    
      
   'finding and replacing text in word file that was opened with text in specific cell from the excel file, not working
    objSelection = wordapp.Selection
    objSelection.Selection.Find.ClearFormatting
    objSelection.Find.Replacement.ClearFormatting
    With Selection.Find
        .Text = "old pathway" 'this will be static text to always find
        .Replacement.Text = Worksheets("HOME").Range("A53").Value 'value in the cell changes depending on user
        .Forward = True
        .Wrap = wdFindContinue
        .Format = False
        .MatchCase = False
        .MatchWholeWord = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
    End With
    Selection.Find.Execute replace:=wdReplaceAll
    
    'would like to update all links in the word doc
    'would like to break specific links, only the excel links, in the word doc
    
    'would like to rename file and save into a different folder at this point, lost on how to code this

End Sub

My main question is how to trigger the find replace sequence in the Word document that I've just opened and "Activated".

When the document opens, I get an error message

run-time error 450
wrong number of arguments or invalid property assignment

Whether Find/Replace will actually complete the job depends on whether you have Word's field code display toggled 'on' (you have no code for that), whether the links are in just the document body, or in headers, footers, etc. as well, and what wrap format those objects have.

The alternative is to explicitly change the linked object source paths and/or filenames in all StoryRanges, etc., for which try:

Sub ReplaceLinksInWordFile()
'Note: A Reference to the Word Object model is required, via Tools|References in the VBE
Dim wdApp As Word.Application, wdDoc As Word.Document, wdRng As Word.Range
Dim wdShp As Word.Shape, wdiShp As Word.InlineShape, wdFld As Word.Field
Dim StrOldPath As String, StrNewPath As String, bStart As Boolean
StrOldPath = "Old Path"
StrNewPath = Worksheets("HOME").Range("A53").Value
bStart = False: On Error Resume Next
Set wdApp = GetObject(, "Word.Application")
If Err.Number <> 0 Then 'Word isn't already running
  Set wdApp = CreateObject("Word.Application")
  bStart = True
End If
On Error GoTo 0
With wdApp
  .Visible = Not bStart
  Set wdDoc = .Documents.Open(Worksheets("HOME").Range("A54").Value, AddToRecentFiles:=False)
  With wdDoc
    For Each wdRng In .StoryRanges
      ' Go through the shapes in the story range.
      For Each wdShp In wdRng.ShapeRange
        With wdShp
          ' Skip over shapes that don't have links to external files.
          If Not .LinkFormat Is Nothing Then
            With .LinkFormat
              If .Type = wdLinkTypeOLE Then
                ' Replace the link to the external file.
                .SourceFullName = Replace(.SourceFullName, StrOldPath, StrNewPath)
                .Update
                .BreakLink
              End If
            End With
          End If
        End With
      Next wdShp
      ' Go through the inlineshapes in the story range.
      For Each wdiShp In wdRng.InlineShapes
        With wdiShp
          ' Skip over inlineshapes that don't have links to external files.
          If Not .LinkFormat Is Nothing Then
            With .LinkFormat
              If .Type = wdLinkTypeOLE Then
                ' Replace the link to the external file.
                .SourceFullName = Replace(.SourceFullName, StrOldPath, StrNewPath)
                .Update
                .BreakLink
              End If
            End With
          End If
        End With
      Next wdiShp
      ' Go through the fields in the story range.
      For Each wdFld In wdRng.Fields
        With wdFld
          ' Skip over fields that don't have links to external files.
          If Not .LinkFormat Is Nothing Then
            With .LinkFormat
              If .Type = wdLinkTypeOLE Then
                ' Replace the link to the external file.
                .SourceFullName = Replace(.SourceFullName, StrOldPath, StrNewPath)
                .Update
                .BreakLink
              End If
            End With
          End If
        End With
      Next wdFld
    Next wdRng
    .SaveAs2 Filename:=StrNewPath & .Name, FileFormat:=.SaveFormat, AddToRecentFiles:=False
    .Close False
  End With
  If bStart = True Then .Quit
End With
MsgBox "Done"
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM