Advertisement
rccharles

FindAndReplaceInFolderVersion2.visualbasic

Aug 31st, 2018
588
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.     Sub FindAndReplaceInFolderVersion2()
  2.  
  3.     ' Find and Replace a string in all documents in a folder
  4.    '
  5.    '  VBA forums
  6.    '     https://www.mrexcel.com/forum/index.php
  7.    '     http://www.vbaexpress.com/forum/forum.php
  8.    '
  9.    '
  10.    '  Descriptions of error processing
  11.    '   https://msdn.microsoft.com/en-us/library/6xx36z07(v=vs.100)?cs-save-lang=1&cs-lang=vb#code-snippet-1
  12.    '   https://www.fmsinc.com/free/newtips/VBA/ErrorHandling/LineNumber.html
  13.    '
  14.    ' To see the code and run, click on the Developer tab then click on the Macros icon.
  15.    '
  16.    ' To see debug messages, open Immediate Window
  17.    '     Word > View > Immediate Window
  18.    '     control + command + g
  19.    '
  20.    ' To run, click on the Blue triangle in the upper right of the Word window.  [ hopefully ]
  21.    '
  22.    ' Permission is hereby granted, free of charge, to any person obtaining a copy
  23.    ' of this software and associated documentation files (the "Software"), to deal
  24.    ' in the Software without restriction, including without limitation the rights
  25.    ' to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  26.    ' copies of the Software, and to permit persons to whom the Software is
  27.    ' furnished to do so, subject to the following conditions:
  28.    '
  29.    ' The above copyright notice and this permission notice shall be included in all
  30.    ' copies or substantial portions of the Software.
  31.    '
  32.    ' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  33.    ' IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  34.    ' FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  35.    ' AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  36.    ' LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  37.    ' OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  38.    ' SOFTWARE.
  39.    '
  40.  
  41.  
  42.       Dim objDoc As Document
  43.       Dim strFile As String
  44.       Dim fileString As String
  45.       Dim MyDir As String
  46.       Dim strError As String
  47.       Dim message, title, defaultValue As String
  48.       Dim strFolder, strReplaceText   As String
  49.       Dim docStringFind As String
  50.       Dim fileExtension As String
  51.       Dim boxTheMsg As String
  52.       Dim Msg As String
  53.    
  54. 10   Debug.Print "...===.===..beginning of program....=======..." & Format(Now(), "dd/mm/yyyy hh:mm:ss.ms")
  55.        
  56.    
  57.        'Debug.Print System.Reflection.MethodBase.GetCurrentMethod().Name
  58.       'Debug.Print System.Diagnositcs.StackTrace()
  59. 11      If Application.Documents.Count >= 1 Then
  60. 12       Debug.Print "current document name is " & ActiveDocument.Name
  61. 13      Else
  62. 14         Debug.Print "No documents are open"
  63. 15      End If
  64.        
  65.       ' pop up input boxes for user to enter folder path, the existing text and replacement text.
  66.      ' Path needs to be like this. Notice no colon in front, but required in back.
  67.      ' Macintosh HD:Users:mac:Documents:word global change:wordMultiwordChange:
  68.      ' Macintosh HD:Users:mac:multidocs:
  69.    
  70. 20  message = "Enter folder path here. " & vbNewLine & "Example:" & vbNewLine & "Macintosh HD:Users:mac:Documents:"  ' Set prompt.
  71. 30  title = "Change All Documents"  ' Set title.
  72. 40  defaultValue = "Macintosh HD:Users:mac:"   ' Set default value.
  73.    ' Display message, title, and default value.
  74. 50  strFolder = InputBox(message, title, defaultValue)
  75. 60  If Len(strFolder) = 0 Then
  76. 70    MsgBox ("Cancelled inputing file path.")
  77. 80    Exit Sub
  78. 90  End If
  79. 100 Debug.Print "length of foder name is " & Len(strFolder) & "  strFolder is " & strFolder
  80.  
  81.        ' Visual basic like to have a ":" at the end, so put it if messing.
  82. 110       If Right(strFolder, 1) <> ":" Then
  83.                 ' end colon is needed
  84. 112          strFolder = strFolder & ":"
  85.                 Debug.Print "  modified strFolder is " & strFolder
  86.  
  87. 114       End If
  88.          
  89.           '  MacScript("do shell script ""command""")
  90.          
  91. 115    On Error GoTo ErrDir
  92. 120    strFile = Dir(strFolder)
  93. 125    On Error GoTo 0
  94. 130    Debug.Print "strFile is " & strFile
  95.    
  96. 140    docStringFind = InputBox("Enter finding text here:")
  97. 150       If Len(docStringFind) = 0 Then
  98. 160           MsgBox ("Cancelled Find string input.")
  99. 170           Exit Sub
  100. 180       End If
  101. 190    Debug.Print "docStringFind  is " & docStringFind
  102.    
  103. 200    strReplaceText = InputBox("Enter replacing text here:")
  104. 210       If Len(strReplaceText) = 0 Then
  105. 220           MsgBox ("Cancelled Replace string input.")
  106. 230           Exit Sub
  107. 240       End If
  108. 250   Debug.Print "strReplaceText is " & strReplaceText
  109. 255
  110.    
  111.         '  Open each file in the folder to search and replace texts. Save and close the file after the action.
  112. 260    While strFile <> ""
  113.               On Error GoTo ErrHandler
  114.  
  115. 270         Debug.Print vbCrLf & "--> strFile is " & strFile
  116.  
  117.    
  118.         'Skip hidden folder format file.
  119. 280     If strFile = ".DS_Store" Then GoTo NextIteration
  120.    
  121.         'Retrieve File Extension
  122. 290    fileExtension = Right(strFile, Len(strFile) - InStrRev(strFile, "."))
  123. 300    Debug.Print "fileExtension is " & fileExtension
  124. 310    If (LCase(fileExtension) <> "doc" And LCase(fileExtension) <> "docx") Then
  125. 320      Debug.Print "skipping " & strFile & " because it doesn't have .doc or .docx entension. "
  126. 330      GoTo NextIteration
  127. 340    End If
  128.    
  129.         'Real work
  130. 350     fileString = strFolder & strFile
  131. 360     Debug.Print "fileString is " & fileString
  132. 370     Set objDoc = Documents.Open(fileName:=fileString)
  133.    
  134. 380     With objDoc
  135. 390       With Selection
  136. 400         .HomeKey Unit:=wdStory
  137. 410         With Selection.Find
  138. 420           .Text = docStringFind
  139. 430           .Replacement.Text = strReplaceText
  140. 440           .Forward = True
  141. 450           .Wrap = wdFindContinue
  142. 460           .Format = False
  143. 470           .MatchCase = False
  144. 480           .MatchWholeWord = False
  145. 490           .MatchWildcards = False
  146. 500           .MatchSoundsLike = False
  147. 510           .MatchAllWordForms = False
  148. 520         End With
  149.  
  150.              ' We are getting the data out of the word structure.  To see if we got it right.
  151. 530       Debug.Print "  Text is -->" & Selection.Find.Text & "<-- Replacement.Text Is -->" & Selection.Find.Replacement.Text & "<--"
  152.  
  153. 540         Selection.Find.Execute Replace:=wdReplaceAll
  154. 550       End With
  155. 560       Debug.Print "  document updated"
  156. 570       objDoc.Save
  157. 575           Debug.Print "  saved"
  158. 580       objDoc.Close
  159. 585            Debug.Print "  closed"
  160. 590     End With
  161.    
  162.  
  163. 600     GoTo NextIteration: ' skip error code
  164.  
  165. ErrDir:
  166. 630     Debug.Print "  --- dir error --- "
  167. 640     boxTheMsg = "An error occured while getting files in the Folder " & strFolder & vbCrLf
  168. 645     boxTheMsg = boxTheMsg & "Verify you correctly typed the folder name." & vbCrLf
  169. 650     boxTheMsg = boxTheMsg & "Error Line: " & Erl & vbCrLf
  170. 670     boxTheMsg = boxTheMsg & "Error: (" & Str(Err.Number) & " ) " & vbCrLf & Err.Description
  171. 680     Debug.Print "boxTheMsg is " & boxTheMsg
  172. 690     MsgBox boxTheMsg, vbCritical
  173.  
  174. 700    On Error GoTo -1  '  clear error .  clears err structure
  175.           ' We have no folder so there isn't anything to do.
  176. 710         GoTo EndOfModule:
  177.  
  178. ErrHandler:
  179. 730     Debug.Print "  --- error --- "
  180. 740     boxTheMsg = "An error occured , while processing document:" & vbCrLf & "  " & strFile & vbCrLf
  181. 750     boxTheMsg = boxTheMsg & "Error Line: " & Erl & vbCrLf
  182. 770     boxTheMsg = boxTheMsg & "Error: (" & Str(Err.Number) & " ) " & vbCrLf & Err.Description
  183. 780     Debug.Print "boxTheMsg is " & boxTheMsg
  184. 790     MsgBox boxTheMsg, vbCritical
  185.  
  186. 795     On Error GoTo -1  '  clear error .  clears err structure
  187.        'try going to the next file.
  188.    
  189. NextIteration:
  190. 800      strFile = Dir()
  191.  
  192. 810   Wend
  193.    
  194. EndOfModule:
  195.  
  196. 820    End Sub  ' FindAndReplaceInFolder(Version2)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement