I'm not sure how to run this macro properly - vba

I need to take existing word files that were created with smart quotes, I have to open each document and replace the quotes, then save and close. I wrote the macro, that works perfectly using the recorder function on word.
Now I've seen people write macros that can run the macro in a loop on each file in the folder but I have no idea where I actually run that macro from.
Sub Macro1()
'
' Macro1 Macro
'
'
ActiveDocument.Convert
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
With Selection.Find
.Text = """"
.Replacement.Text = """"
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Selection.Find.Execute Replace:=wdReplaceAll
With Selection.Find
.Text = "'"
.Replacement.Text = "'"
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Selection.Find.Execute Replace:=wdReplaceAll
ChangeFileOpenDirectory _
"\\EXPRESS-SERVER\MTMQuote\Quote Archive\Quote Archive (Out Dated)\Expert Quotes\120001-130000 (2013-)\125001-126000 (2015)\Updated\"
ActiveDocument.SaveAs2 FileName:= _
(ActiveDocument.Name) _
, FileFormat:=wdFormatDocumentDefault, LockComments:=False, Password:="", _
AddToRecentFiles:=True, WritePassword:="", ReadOnlyRecommended:=False, _
EmbedTrueTypeFonts:=False, SaveNativePictureFormat:=False, SaveFormsData _
:=False, SaveAsAOCELetter:=False, CompatibilityMode:=15
ActiveDocument.Close
Application.Quit
End Sub
How do I run this over and over? there are about 1000 files in the folder on my desktop called "MTMUPDATES"

Use this:
(but don't name them all the same thing, make whatever you use to name the docs count up or something)
Sub replacer()
Dim MyDialog As FileDialog, GetStr(1 To 1000) As String '1000 files is the maximum applying this code
On Error Resume Next
Set MyDialog = Application.FileDialog(msoFileDialogFilePicker)
With MyDialog
.Filters.Clear
.Filters.Add "All WORD File ", "*.*", 1
.AllowMultiSelect = True
i = 1
If .Show = -1 Then
For Each stiSelectedItem In .SelectedItems
GetStr(i) = stiSelectedItem
i = i + 1
Next
i = i - 1
End If
Application.ScreenUpdating = False
For j = 1 To i Step 1
Set Doc = Documents.Open(FileName:=GetStr(j), Visible:=True)
Windows(GetStr(j)).Activate
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
With Selection.Find
.Text = "'" 'find what
.Replacement.Text = "'" 'replace with
.Forward = True
.Wrap = wdFindAsk
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchByte = True
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Selection.Find.Execute Replace:=wdReplaceAll
Application.Run macroname:="NEWMACROS"
docname = InputBox("Enter file name", "docname") 'replace this with some sort of naming device or use the next thing
newname = docname & ".doc"
ActiveDocument.SaveAs FileName:=newname
'ActiveDocument.Save 'use this if you just want to save the document. remove the apostrophe before and delete the previous little expression or put apostrophes in front of it
ActiveWindow.Close
Next
Application.ScreenUpdating = True
End With
MsgBox "operation end, please view", vbInformation
End Sub

Related

Selection.Find within a range

I am not familiar with Word VBA and am having a problem with Selection.Find.
I want to replace commas by decimal points in a range of cells in a table. However I can only get Selection.Find to replace either all commas in the document or only the first comma in the range.
What I would like is something like Selection.Replace What:=".", Replacement:="," in Excel, but Word does not support that.
Suggestions very gratefully received!
CJ
Sub Replace_Percent_Separator()
'Correct percent separator in row 6, table 2
Dim PcentCells As Range
Path = "C:\xxx\Word\"
file = Dir(Path & "*.docx")
Application.DisplayAlerts = False
Application.ScreenUpdating = False
Do While file <> ""
Documents.Open Filename:=Path & file
With ActiveDocument
Set PcentCells = .Range(Start:=.Tables(2).Cell(6, 2).Range.Start, _
End:=.Tables(2).Cell(6, 10).Range.End)
PcentCells.Select
With Selection.Find
.Text = ","
.Replacement.Text = "."
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
.Execute Replace:=wdReplaceAll '<-- replaces throughout document
'.Execute Replace:=wdReplaceOne '<-- replaces in first cell but no other cells
End With
End With
ActiveDocument.Save
ActiveDocument.Close
file = Dir()
Loop
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
Given your problem description, your code can be reduced to:
Sub Replace_Percent_Separator()
'Correct percent separator in row 6, table 2
file = Dir("C:\xxx\Word\*.docx")
Do While file <> ""
Documents.Open FileName:=Path & file, AddToRecentFiles:=False, Visible:=False
With ActiveDocument
With .Tables(2).Row(6).Range.Find
.Text = ","
.Replacement.Text = "."
.Forward = True
.Wrap = wdFindStop
.Format = False
.Execute Replace:=wdReplaceAll
End With
.Close SaveChanges:=True
End With
file = Dir()
Loop
End Sub
As can be seen, there is no need to select anything and, by using wdFindStop instead of wdFindContinue, the Find/Replace stops where it should.

Convert RTF to DOCX with VBA

I am a novice at this but I convert .RTF files in a whole folder to .DOCX files using this code below.
Sub BatchConvertToDocx()
Application.ScreenUpdating = False
Dim strFolder As String, strFile As String, wdDoc As Document
strFolder = GetFolder
If strFolder = "" Then Exit Sub
strFile = Dir(strFolder & "\*.rtf", vbNormal)
While strFile <> ""
Set wdDoc = Documents.Open(FileName:=strFolder & "\" & strFile, AddToRecentFiles:=False, Visible:=False)
With wdDoc
.SaveAs2 FileName:=Left(.FullName, InStrRev(.FullName, ".")) & "docx", FileFormat:=wdFormatXMLDocument, AddToRecentFiles:=False
.Close wdDoNotSaveChanges
End With
strFile = Dir()
Wend
Set wdDoc = Nothing
App
lication.ScreenUpdating = True
End Sub
Function GetFolder() As String
Dim oFolder As Object
GetFolder = ""
Set oFolder = CreateObject("Shell.Application").BrowseForFolder(0, "Choose a folder", 0)
If (Not oFolder Is Nothing) Then GetFolder = oFolder.Items.Item.Path
Set oFolder = Nothing
End Function
Could somebody please tell me how to hide text that is between square braces in the output .docx file?
For example
Hi [This is the text that should be hidden] there.
Also, while converting the .docx file back to .rtf file, the text should reappear in the output .rtf file.
I see 2 different ways to do this.
Hard remove/delete the text with find/replace. Here I see no possibility to bring that text back in any way. Gone is gone.
Hide the text from printing with formatting it as hidden text.
Hard Remove
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
With Selection.Find
.Text = "\[*\]"
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchAllWordForms = False
.MatchSoundsLike = False
.MatchWildcards = True
End With
Selection.Find.Execute Replace:=wdReplaceAll
Hide from printing
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
Selection.Find.Replacement.Font.Hidden = True
With Selection.Find
.Text = "\[*\]"
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindContinue
.Format = True
.MatchCase = False
.MatchWholeWord = False
.MatchAllWordForms = False
.MatchSoundsLike = False
.MatchWildcards = True
End With
Selection.Find.Execute Replace:=wdReplaceAll
'if this line is not used the text might be visible on the screen but not on print.
ActiveWindow.ActivePane.View.ShowAll = False
Unhiding the text from printing
This should un hide the text when converting back to .rtf
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
Selection.Find.Font.Hidden = True
Selection.Find.Replacement.Font.Hidden = False
With Selection.Find
.Text = "\[*\]"
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindContinue
.Format = True
.MatchCase = False
.MatchWholeWord = False
.MatchAllWordForms = False
.MatchSoundsLike = False
.MatchWildcards = True
End With
Selection.Find.Execute Replace:=wdReplaceAll

.Find Loop Word 2013

I have a document that has plain text and I want to do some preformatting before I move it to Access. Currently, I'm in Word trying to separate the formatting into titles and text. The document has hundreds of titles and after each title small explanation text (it's an error book with explanations for one machine).
I am trying to put a unique string at the end of a lane that starts with "start-of-title" unique string.
I want to make a macro that finds that string, then goes to the end of the lane and writes " end-of-title" and do that till there are results found.
What I've done so far, and works once, is the following:
Sub test3()
Selection.Find.ClearFormatting
With Selection.Find
.Text = "startoftitle "
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindAsk
.Format = False
.MatchCase = True
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Selection.Find.Execute
Selection.EndKey Unit:=wdLine
Selection.TypeText Text:=" endoftitle"
End Sub
I've tried doing loops, but sadly I wasn't able to do the right syntax. The problem is that I can't make it loop till there are no results found...
This should do it
Sub test3()
Const STARTTOKEN = "startoftitle "
Const ENDTOKEN = " endoftitle"
For i = 1 To ThisDocument.Paragraphs.Count
If ThisDocument.Paragraphs(i).Range.Style = "Title" _
And Left(ThisDocument.Paragraphs(i).Range.Text, Len(STARTTOKEN)) <> STARTTOKEN Then
ThisDocument.Paragraphs(i).Range.Text = STARTTOKEN & ThisDocument.Paragraphs(i).Range.Text & ENDTOKEN
End If
Next i
End Sub
I managed to solve it before checking what you've written. Thank you for your help!
Here is the code for anyone with the same problem:
Sub test3()
'
' test3 Macro
'
'
Selection.Find.ClearFormatting
With Selection.Find
.Text = " startoftitle "
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindStop
.Format = False
.MatchCase = True
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Do While Selection.Find.Execute = True
Selection.EndKey Unit:=wdLine
Selection.TypeText Text:=" endoftitle"
Loop
End Sub

Recorded "Find+Replace All" macro finds only the first instance when run as a macro

I set a user Find+Replace All macro, to find and replace all instances of a particular text, and it worked as planned.
However when I recorded that operation as a macro, and ran it, it replaced just the first instance of the find text. What am I doing wrong?
The code that was recorded is a further below.
Sub Macro25()
'
' Macro25 Macro
'
'
Selection.Find.ClearFormatting
Selection.Find.Style = ActiveDocument.Styles("Body Text")
With Selection.Find.ParagraphFormat
With .Shading
.Texture = wdTextureNone
.ForegroundPatternColor = wdColorBlack
.BackgroundPatternColor = wdColorBlack
End With
.Borders.Shadow = False
End With
Selection.Find.Replacement.ClearFormatting
Selection.Find.Replacement.Style = ActiveDocument.Styles("Body Text 2")
With Selection.Find.Replacement.ParagraphFormat
With .Shading
.Texture = wdTextureNone
.ForegroundPatternColor = wdColorBlack
.BackgroundPatternColor = wdColorBlack
End With
.Borders.Shadow = False
End With
With Selection.Find
.Text = ""
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindContinue
.Format = True
.MatchCase = False
.MatchWholeWord = False
.MatchKashida = False
.MatchDiacritics = False
.MatchAlefHamza = False
.MatchControl = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Selection.Find.Execute Replace:=wdReplaceAll
End Sub
The macro is only replacing the text that you have selected when you run the macro. That's what the word Selection means.
If you want the Find/Replace to happen for your whole document, you need to replace Selection in your macro with ActiveDocument.
Thanks for the answer.
So moving on here ... below is the code I wrote myself. It is based on the code produced by the Macro recorder.
My code does not use the same idea of Selection. It uses a rng Range object.
However I get the same effect: that it is finding only the first instance of something.
Function ExecReplaceStyle(strSourceStyle As String, strDestinationStyle As String) As Integer
On Error GoTo ErrorHandler
Dim rng As Range
Dim ret As Integer
ExecReplaceStyle = 0
Set rng = docActiveDoc.Range
With rng.Find
.ClearFormatting
.Style = ActiveDocument.Styles(strSourceStyle)
.Replacement.Style = ActiveDocument.Styles(strDestinationStyle)
.Text = ""
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindContinue
.Forward = True
.Format = True
.MatchCase = False
.MatchWholeWord = False
.MatchKashida = False
.MatchDiacritics = False
.MatchAlefHamza = False
.MatchControl = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
rng.Select
rng.Find.Execute Replace:=wdReplaceAll
ExecReplaceStyle = ret
Exit Function
ErrorHandler:
ExecReplaceStyle = Err.Number
ErrDescription = Err.Description
Resume Next
End Function
The Selection.Find.Execute Replace:=wdReplaceAll after the End With should search and replace across the whole document.

Word Macro that would find and create hyperlink of similar words

This is the code of my macro (Macro1):
Sub Macro1()
'
' Macro1 Macro
'
Selection.Find.ClearFormatting
With Selection.Find
.Text = "REQ"
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = True
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Selection.Find.Execute
Selection.MoveRight Unit:=wdCharacter, Count:=8, Extend:=wdExtend
Selection.Copy
ActiveDocument.Hyperlinks.Add Anchor:=Selection.Range, Address:= _
"http://www.neki.com/REQ12345678", SubAddress:="", ScreenTip:="", _
TextToDisplay:="REQ12345678"
End Sub
The code works fine finding the REQxxxxxxxx texts, but then pastes wrong TextToDisplay and wrong ending of an address. Instead of REQ12345678 in both places should be pastet the same text I copied before at: Selection.Copy.
I also have no idea, how to create a loop or something like that, so that Macro1 would be running until it reaches the end of a document.
Help me, please!
Hey, I solved the 1st problem with creating hyperlinks. Now I have to loop that "hyperlink" macro. I decided to create another macro, that would loop the first one. Here is my code:
Sub Macro2()
'
' Macro2 Macro
'
Do Until ActiveDocument.Bookmarks.Exists("Konec")
Application.Run MacroName:="Macro1"
Loop
End Sub
Macro1 works perfectly fine, but I can't figure it out how to loop it until the end of document - Until the ending bookmark...
I used the following code to link selected text to similar text that appears later in the document.
Sub Macro1()
'
' Macro1 Macro
'
'
With Selection.Find
.Text = Selection
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = True
.MatchWholeWord = True
.MatchWildcards = True
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Selection.Find.Execute
With ActiveDocument.Bookmarks
.Add Range:=Selection.Range, Name:=Selection
.DefaultSorting = wdSortByName
.ShowHidden = False
End With
With Selection.Find
.Text = Selection
.Replacement.Text = ""
.Forward = False
.Wrap = wdFindContinue
.Format = False
.MatchCase = True
.MatchWholeWord = True
.MatchWildcards = True
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Selection.Find.Execute
ActiveDocument.Hyperlinks.Add Anchor:=Selection.Range, Address:="", _
SubAddress:=Selection, ScreenTip:="", TextToDisplay:=Selection
End Sub