View Single Post
 
Old 09-07-2023, 08:05 AM
alejandro21805 alejandro21805 is offline Windows 10 Office 2019
Novice
 
Join Date: Sep 2023
Posts: 3
alejandro21805 is on a distinguished road
Default

Hello gmaxey

Thank you very much for your help. I modified the macro to find keywords between ## and $$ symbols, and it works. I hope it will be useful for everyone.

Code:
Sub ReplaceKeyWord()
    Dim oRng As Range
    Dim strFolderPath As String
    Dim strKeyword As String
    Dim strFileName As String
    
    ' Define the folder where the files to be inserted are located
    strFolderPath = "C:\Users\File\" ' Replace with the correct path
    
    ' Define the keyword pattern between "##" and "$$"
    strKeyword = "##*$$" ' This pattern will search for any word that matches the pattern
    
    Set oRng = ActiveDocument.Content
    
    ' Loop to find and replace all instances of the keyword
    Do While oRng.Find.Execute(FindText:=strKeyword, MatchWildcards:=True)
        ' Get the filename to insert
        strFileName = strFolderPath & Mid(oRng.Text, 3, Len(oRng.Text) - 4) & ".docx"
        
        ' Check if the file exists
        If Dir(strFileName) <> "" Then
            ' Delete the found keyword
            oRng.Delete
            ' Insert the content of the file
            oRng.InsertFile FileName:=strFileName
        Else
            ' If the file doesn't exist, display an error message
            MsgBox "The file '" & strFileName & "' was not found in the specified folder.", vbExclamation, "File Not Found"
        End If
        
        ' Move the range to the end of the document to continue searching
        oRng.Collapse Direction:=wdCollapseEnd
    Loop
    
    ' Clean up and release the Range object
    Set oRng = Nothing
End Sub
Reply With Quote