Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Sub FindAndReplaceInFolderVersion2()
- ' Find and Replace a string in all documents in a folder
- '
- ' VBA forums
- ' https://www.mrexcel.com/forum/index.php
- ' http://www.vbaexpress.com/forum/forum.php
- '
- '
- ' Descriptions of error processing
- ' https://msdn.microsoft.com/en-us/library/6xx36z07(v=vs.100)?cs-save-lang=1&cs-lang=vb#code-snippet-1
- ' https://www.fmsinc.com/free/newtips/VBA/ErrorHandling/LineNumber.html
- '
- ' To see the code and run, click on the Developer tab then click on the Macros icon.
- '
- ' To see debug messages, open Immediate Window
- ' Word > View > Immediate Window
- ' control + command + g
- '
- ' To run, click on the Blue triangle in the upper right of the Word window. [ hopefully ]
- '
- ' Permission is hereby granted, free of charge, to any person obtaining a copy
- ' of this software and associated documentation files (the "Software"), to deal
- ' in the Software without restriction, including without limitation the rights
- ' to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- ' copies of the Software, and to permit persons to whom the Software is
- ' furnished to do so, subject to the following conditions:
- '
- ' The above copyright notice and this permission notice shall be included in all
- ' copies or substantial portions of the Software.
- '
- ' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- ' IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- ' FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- ' AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- ' LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- ' OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
- ' SOFTWARE.
- '
- Dim objDoc As Document
- Dim strFile As String
- Dim fileString As String
- Dim MyDir As String
- Dim strError As String
- Dim message, title, defaultValue As String
- Dim strFolder, strReplaceText As String
- Dim docStringFind As String
- Dim fileExtension As String
- Dim boxTheMsg As String
- Dim Msg As String
- 10 Debug.Print "...===.===..beginning of program....=======..." & Format(Now(), "dd/mm/yyyy hh:mm:ss.ms")
- 'Debug.Print System.Reflection.MethodBase.GetCurrentMethod().Name
- 'Debug.Print System.Diagnositcs.StackTrace()
- 11 If Application.Documents.Count >= 1 Then
- 12 Debug.Print "current document name is " & ActiveDocument.Name
- 13 Else
- 14 Debug.Print "No documents are open"
- 15 End If
- ' pop up input boxes for user to enter folder path, the existing text and replacement text.
- ' Path needs to be like this. Notice no colon in front, but required in back.
- ' Macintosh HD:Users:mac:Documents:word global change:wordMultiwordChange:
- ' Macintosh HD:Users:mac:multidocs:
- 20 message = "Enter folder path here. " & vbNewLine & "Example:" & vbNewLine & "Macintosh HD:Users:mac:Documents:" ' Set prompt.
- 30 title = "Change All Documents" ' Set title.
- 40 defaultValue = "Macintosh HD:Users:mac:" ' Set default value.
- ' Display message, title, and default value.
- 50 strFolder = InputBox(message, title, defaultValue)
- 60 If Len(strFolder) = 0 Then
- 70 MsgBox ("Cancelled inputing file path.")
- 80 Exit Sub
- 90 End If
- 100 Debug.Print "length of foder name is " & Len(strFolder) & " strFolder is " & strFolder
- ' Visual basic like to have a ":" at the end, so put it if messing.
- 110 If Right(strFolder, 1) <> ":" Then
- ' end colon is needed
- 112 strFolder = strFolder & ":"
- Debug.Print " modified strFolder is " & strFolder
- 114 End If
- ' MacScript("do shell script ""command""")
- 115 On Error GoTo ErrDir
- 120 strFile = Dir(strFolder)
- 125 On Error GoTo 0
- 130 Debug.Print "strFile is " & strFile
- 140 docStringFind = InputBox("Enter finding text here:")
- 150 If Len(docStringFind) = 0 Then
- 160 MsgBox ("Cancelled Find string input.")
- 170 Exit Sub
- 180 End If
- 190 Debug.Print "docStringFind is " & docStringFind
- 200 strReplaceText = InputBox("Enter replacing text here:")
- 210 If Len(strReplaceText) = 0 Then
- 220 MsgBox ("Cancelled Replace string input.")
- 230 Exit Sub
- 240 End If
- 250 Debug.Print "strReplaceText is " & strReplaceText
- 255
- ' Open each file in the folder to search and replace texts. Save and close the file after the action.
- 260 While strFile <> ""
- On Error GoTo ErrHandler
- 270 Debug.Print vbCrLf & "--> strFile is " & strFile
- 'Skip hidden folder format file.
- 280 If strFile = ".DS_Store" Then GoTo NextIteration
- 'Retrieve File Extension
- 290 fileExtension = Right(strFile, Len(strFile) - InStrRev(strFile, "."))
- 300 Debug.Print "fileExtension is " & fileExtension
- 310 If (LCase(fileExtension) <> "doc" And LCase(fileExtension) <> "docx") Then
- 320 Debug.Print "skipping " & strFile & " because it doesn't have .doc or .docx entension. "
- 330 GoTo NextIteration
- 340 End If
- 'Real work
- 350 fileString = strFolder & strFile
- 360 Debug.Print "fileString is " & fileString
- 370 Set objDoc = Documents.Open(fileName:=fileString)
- 380 With objDoc
- 390 With Selection
- 400 .HomeKey Unit:=wdStory
- 410 With Selection.Find
- 420 .Text = docStringFind
- 430 .Replacement.Text = strReplaceText
- 440 .Forward = True
- 450 .Wrap = wdFindContinue
- 460 .Format = False
- 470 .MatchCase = False
- 480 .MatchWholeWord = False
- 490 .MatchWildcards = False
- 500 .MatchSoundsLike = False
- 510 .MatchAllWordForms = False
- 520 End With
- ' We are getting the data out of the word structure. To see if we got it right.
- 530 Debug.Print " Text is -->" & Selection.Find.Text & "<-- Replacement.Text Is -->" & Selection.Find.Replacement.Text & "<--"
- 540 Selection.Find.Execute Replace:=wdReplaceAll
- 550 End With
- 560 Debug.Print " document updated"
- 570 objDoc.Save
- 575 Debug.Print " saved"
- 580 objDoc.Close
- 585 Debug.Print " closed"
- 590 End With
- 600 GoTo NextIteration: ' skip error code
- ErrDir:
- 630 Debug.Print " --- dir error --- "
- 640 boxTheMsg = "An error occured while getting files in the Folder " & strFolder & vbCrLf
- 645 boxTheMsg = boxTheMsg & "Verify you correctly typed the folder name." & vbCrLf
- 650 boxTheMsg = boxTheMsg & "Error Line: " & Erl & vbCrLf
- 670 boxTheMsg = boxTheMsg & "Error: (" & Str(Err.Number) & " ) " & vbCrLf & Err.Description
- 680 Debug.Print "boxTheMsg is " & boxTheMsg
- 690 MsgBox boxTheMsg, vbCritical
- 700 On Error GoTo -1 ' clear error. clears err structure
- ' We have no folder so there isn't anything to do.
- 710 GoTo EndOfModule:
- ErrHandler:
- 730 Debug.Print " --- error --- "
- 740 boxTheMsg = "An error occured , while processing document:" & vbCrLf & " " & strFile & vbCrLf
- 750 boxTheMsg = boxTheMsg & "Error Line: " & Erl & vbCrLf
- 770 boxTheMsg = boxTheMsg & "Error: (" & Str(Err.Number) & " ) " & vbCrLf & Err.Description
- 780 Debug.Print "boxTheMsg is " & boxTheMsg
- 790 MsgBox boxTheMsg, vbCritical
- 795 On Error GoTo -1 ' clear error. clears err structure
- 'try going to the next file.
- NextIteration:
- 800 strFile = Dir()
- 810 Wend
- EndOfModule:
- 820 End Sub ' FindAndReplaceInFolder(Version2)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement