How to add table captions in MS Word using macros - vba

I am trying to amend captions to 100 existing tables in MS Word. To avoid this tedious process I was hoping to use the built-in VB macro functionality.
If my table is inside the contents of the document in the section of:
Intro
1.1 Goals
I want the table caption to be amended with "Intro - Goals". If the table caption is already 'Table 1-1' I want it to read:
Table 1-1 Intro Goals
after the macro runs, is that possible? How?

The script below is a batch process that does a find/replace routine on all the Word files in a folder.
Sub FindReplaceAll()
Dim MyDialog As FileDialog, GetStr(1 To 100) As String
'100 files is the maximum applying this code
On Error Resume Next
Set MyDialog = Application.FileDialog(msoFileDialogFilePicker)
With MyDialog
.Filters.Clear
.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 = "Marriott International" 'Find What
.Replacement.Text = "Marriott" '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"
ActiveDocument.Save
ActiveWindow.Close
Next
Application.ScreenUpdating = True
End With
MsgBox "operation end, please view", vbInformation
End Sub
' The idea comes from here.
' https://www.extendoffice.com/documents/word/1002-word-replace-multiple-files.html

Related

VBA Word, Remove Specific Highlighting Color "Red" get stuck some times at infinite loop

I want to delete the red highlighting color from the MS Word document.
Explanation:
I made a module in MS Word documents that search/find any text highlighting with red color - a text marked with red from the tool shown in the image below. The following code is either working fine or make the MS Word stop responding. I'm not sure why it gets crashing, but I guess due to the loop that I am using. I wish there is something like: .Replacement.HighlightColorIndex = wdred ; and then .Execute Replace:=wdReplaceAll ; instead of the loop.
The VBA code that I wrote:
Sub RemoveSpecificHighlightingColor()
'
' Remove Specific Highlighting Color Macro
' This Macro go through the document and search for any Red color highlighting word and remove it
' colors code: https://learn.microsoft.com/en-us/office/vba/api/word.wdcolorindex
'
Selection.GoTo wdGoToPage, wdGoToAbsolute, 1 'Start at the top of the document
Selection.Find.ClearFormatting
Selection.Find.Highlight = True
Selection.Find.Replacement.ClearFormatting
With Selection.Find
.Text = ""
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindStop 'stop at the end of the document
.Format = True
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
Do While (.Execute(Forward:=True) = True) = True
DoEvents 'keeps Word responsive
If Selection.Range.HighlightColorIndex = wdRed Then
Selection.Range.Delete
End If
Loop
MsgBox "Done!" ' just for testing
End With
End Sub
Some explanation about the code:
I noticed if I select at the middle of the document then run the code, the code start from the mouse selection not from the top. This is why I mentioned the first statement.
Some of the code I got from the record marco feature and from help online. The record marco detect all highlighting color not specific color.
I used Selection.Find so I selected .Wrap = wdFindStop
There is no difference if I keep or remove Format, MatchCase, MatchWholeWord, MatchWildcards, MatchSoundsLike, and MatchAllWordForms.
The main issue is the While loop or any loop that I am using. The one shown in the code check for all highlighting colors and if the color is red, then remove it, otherwise check for another.
Any help is appreciated, thanks!
The big problem with your code is that you are using the Selection object. When you select things in your code the screen has to be redrawn with each change of selection. As Selection.Find selects every match it finds that is a lot of redrawing.
In this instance you can avoid using Selection by using a Range object instead (ActiveDocument.Content is a range). When you use .Find with a range the range is redefined each time a match is found, enabling you to change the properties of that range.
Sub RemoveSpecificHighlightingColor()
Application.ScreenUpdating = False
With ActiveDocument.Content
With .Find
.ClearFormatting
.Replacement.ClearFormatting
.Highlight = True
.Text = ""
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindStop 'stop at the end of the document
.Format = True
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Do While .Find.Execute = True
If .HighlightColorIndex = wdRed Then .Delete
Loop
End With
Application.ScreenUpdating = True
End Sub
For example:
Sub Demo()
Application.ScreenUpdating = False
With ActiveDocument.Range
With .Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = ""
.Replacement.Text = ""
.Format = True
.Forward = True
.Highlight = True
.Wrap = wdFindStop
End With
Do While .Find.Execute
If .HighlightColorIndex = wdRed Then .Delete
'The next If ... End If block is needed if the highlighted content could be in a table
If .Information(wdWithInTable) = True Then
If .End = .Cells(1).Range.End - 1 Then
.End = .Cells(1).Range.End
.Collapse wdCollapseEnd
If .Information(wdAtEndOfRowMarker) = True Then
.End = .End + 1
End If
End If
End If
'The next line is needed if the highlighted content could include the final paragraph break
If .End = ActiveDocument.Range.End Then Exit Do
.Collapse wdCollapseEnd
Loop
End With
Application.ScreenUpdating = True
End Sub
Do note that there's a bug in Word's Find which means it won't find anything if the document consists of a single highlighted paragraph. Additionally, I haven't included code to test whether a found range spans some text as well as part of a field or spans two or more highlight colours. Consequently, neither condition will be processed.
I tried to trace the issue. What I noticed is, in some documents only (mixed of .doc and .docx file type), once I run the code, it goes through the document pages and finds and deletes the red highlighting color, that once all are replaced, the MS Word stuck. Once the MS Word got stuck, the cursor is changing rapidly, as if the screen has to be redrawn, and after a few seconds the program stops responding, and even if I wait for a while it will be stuck until I force to close the MS Word. This happened with or without red highlighting color in the document.
Explanation of the code:
The code runs each page alone by making the code start from the first page and count the number of pages. Then go through each page and select the text.
Apply the filtering code and deleting for the specific selection only, then check for a new page.
I treated the pause/stuck as a bouncing button without a pull-up or pull-down resistor i.e., once the physical button is pressed it fluctuate before it reaches a steady state.
Iteration...
The final code that I used, and It's now working for all documents is shown below:
Sub RemoveSpecificHighlightingColor()
'
' Remove Specific Highlighting Color Macro
' This Macro go through the document and search for any Red color highlighting word and remove it
' colors code: https://learn.microsoft.com/en-us/office/vba/api/word.wdcolorindex
'
Dim NumberOfAllPages As Integer
' Dim LastPageNumber As Integer
Dim PageNumber As Integer
Dim TempCounter As Integer
Dim TemoEnd As Long
Selection.Find.ClearFormatting
PageNumber = 1 'Starting page
NumberOfAllPages = ActiveDocument.ActiveWindow.Panes(1).Pages.Count
' LastPageNumber = 3 'Last page to reach - for testing
Selection.GoTo wdGoToPage, wdGoToAbsolute, PageNumber 'GoTo Page PageNumber
' Debug.Print "Start"
While PageNumber - 1 < NumberOfAllPages 'LastPageNumber
DoEvents 'keeps document responsive
Selection.GoTo wdGoToPage, wdGoToAbsolute, PageNumber 'GoTo Page PageNumber
Selection.Bookmarks("\Page").Select 'Select all the text in the page
With Selection.Find
.Highlight = True
.Text = ""
.Replacement.Text = ""
.Forward = True
Do While (.Execute(Forward:=True) = True) = True
DoEvents 'keeps document responsive
If Selection.Range.HighlightColorIndex = wdRed Then Selection.Range.Delete
' If the process is stuck at the same location for while then (50 times) it mean the page is full check from Red Highlighting Color
If ActiveWindow.Selection.End = TemoEnd Then
TempCounter = TempCounter + 1
End If
If TempCounter > 50 Then Exit Do
' Debug.Print ActiveDocument.Range.End
' Debug.Print ActiveWindow.Selection.End
TemoEnd = ActiveWindow.Selection.End
Loop
End With
TempCounter = 0 ' reset counter
' Debug.Print PageNumber
PageNumber = PageNumber + 1
Wend
End Sub
I can't tell you where your error is, but here's a working code
Sub UNHIGHCOLOR()
'HOW MANY HIGHLIGHT REGIONS ARE - store to AAAM
Selection.HomeKey wdStory
'HIG_COUNT Macro
'CTRL-FN-SHIFT TO BREAK
START:
'Selection.HomeKey wdStory
Selection.Find.ClearFormatting
Selection.Find.Highlight = True
With Selection.Find
.Text = ""
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindStop
.Format = True
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
.Execute
If .Found Then
'MsgBox "found"
If Selection.Range.HighlightColorIndex = wdRed Then
'MsgBox "RED"
'Selection.Range.HighlightColorIndex = 0
End If
AAAM = AAAM + 1
GoTo START
Else
'MsgBox "not found"
'MsgBox AAAM & " HIGH REGIONS"
End If
End With
Selection.HomeKey wdStory
'*********************************************************
'FOR AAAM REGIONS CHANGE HIGHLIGHT RED COLORS TO NO COLOR
For X = 1 To AAAM + 1
'UNHIGHCOLOR_RED_NEXT
Selection.Find.ClearFormatting
Selection.Find.Highlight = True
With Selection.Find
.Text = ""
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindStop
.Format = True
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
.Execute
End With
If Selection.Range.HighlightColorIndex = wdRed Then
'MsgBox "RED"
Selection.Range.HighlightColorIndex = 0 'NO COLOR
End If
Selection.Collapse (wdCollapseEnd) 'TO FIND NEXT
Next
End Sub

How to break clipboard into multiple strings in Microsoft Word Using a VBA Macro?

I'm trying to replace multiple "placeholders" in a single word document by breaking the text in my clipboard into various string.
Sample clipboard text would be something like this:
Placeholder1=
Test1
Placeholder2=
First sentence.
Second Sentence.
Third Sentence.
Placeholder3=
2044 to 2045
Placeholder4=
five
So far, I can take the text my clipboard and paste it to replace a single placeholder. I can also insert the date.
Here's what I have so far:
Sub FillPlaceHolder()
'Prints a new label in bottom left of sticker sheet based on clipboard data
'To use the clipboard you need a reference to the following library
'Go to Tools > References and select Microsoft Forms Object Library
'If it's not visible, click browse and find FM20.dll in your system32 folder
Dim DataObj As MSForms.DataObject
Set DataObj = New MSForms.DataObject
'Set error handling, will skip the code if the clipboard is empty
On Error GoTo Error
'Set variable for clipboard string
Dim myString As String
Dim myDate As Date
'Get data object from clipboard
DataObj.GetFromClipboard
'Set mystring to the first text in the clipboard
myString = DataObj.GetText(1)
myString = ClearFormatting
'Open the Word document
Documents.Open FileName:=GetFolder() & "Auden_perm_template.doc"
'Replaces the PlaceHolder text
With Selection.Find
.Text = "PLACEHOLDER2"
.Replacement.ClearFormatting
.Replacement.Text = myString
.Execute
End With
Selection.Paste
TodaysDate2
InsertDate
TodaysDate
InsertDate
'
'BELOW TO ADD PRINT
' Application.OnTime When:=Now + TimeValue("00:00:10"), Name:="Print_Label"
'Process this error for empty clipboards
Error:
If Err <> 0 Then MsgBox "Data on clipboard is empty"
End Sub
Sub TodaysDate2()
'
' Macro3Date Macro
'
'
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
With Selection.Find
.Text = "TODAYSDATE2"
.Replacement.Text = "02/25/19"
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Selection.Find.Execute
Selection.Find.Execute
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
With Selection.Find
.Text = "TODAYSDATE2"
.Replacement.Text = "02/25/19"
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
End Sub
Sub InsertDate()
'
' Macro3 Macro
'
'
Selection.Fields.Add Range:=Selection.Range, Type:=wdFieldDate
End Sub
Sub TodaysDate()
'
' Macro3Date Macro
'
'
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
With Selection.Find
.Text = "TODAYSDATE"
.Replacement.Text = "02/25/19"
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Selection.Find.Execute
Selection.Find.Execute
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
With Selection.Find
.Text = "TODAYSDATE2"
.Replacement.Text = "02/25/19"
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
End Sub
I'm struggling to figure out how to break the clipboard into multiple strings. What do you recommend?
You can break the string into an array using Split
For example:
myString = split(DataObj.GetText(1),vblf)
Change the Dim for myString from String to Variant
Then you can loop through the array with something like:
For X = lbound(myString) to ubound(myString)
If myString(X) = "PLACEHOLDER1" then
'Do Something when placeholder1 found
ElseIf myString(X) = "PLACEHOLDER2" then
'Do Something when placeholder2 found
ElseIf myString(X) = "PLACEHOLDER3" then
'Do Something when placeholder3 found
End IF
next
You will need to Dim X as a Long
You can set up a couple of variables to set the start and end of each placeholder then you can cycle through those parts joining each element back together with a vblf as the delimeter in order to create what you want.

Word 2016: How do I find and replace all paragraph marks only in tables?

I have a 300+ page Word 2016 doc imported from another program that has a huge amount of tables. In every table cell there is at least one paragraph mark. I want to Find and Replace every single paragraph mark with nothing, but only in tables (there are tons of other paragraph marks in normal text that I want to leave alone).
I can use the Find/Replace dialog to do it manually, but that will take a huge amount of clicks and time. There is no "only in tables" option in the dialog box, so it seems I need to craft a VBA macro but I've never done that before. Below is the macro produced by recording the action of "Find/Replace a paragraph mark in one table". What needs to be changed to enable this to tackle all the tables at once?
Dim mytable As Table
Application.ScreenUpdating = False
For Each mytable In ActiveDocument.Tables
mytable.Range.Editors.Add wdEditorEveryone
Next
ActiveDocument.SelectAllEditableRanges (wdEditorEveryone)
ActiveDocument.DeleteAllEditableRanges (wdEditorEveryone)
Application.ScreenUpdating = True
End Sub
Sub FindReplaceInTable()
'
' FindReplaceInTable Macro
'
'
Selection.Tables(1).Select
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
With Selection.Find
.Text = "^p"
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindAsk
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchKashida = False
.MatchDiacritics = False
.MatchAlefHamza = False
.MatchControl = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Selection.Find.Execute
End Sub
Thanks in advance.
Try:
Sub ClearTblParaBreaks()
Application.ScreenUpdating = False
Dim Tbl As Table
For Each Tbl In ActiveDocument.Tables
With Tbl.Range.Find
.ClearFormatting
.Replacement.ClearFormatting
.Format = False
.Forward = True
.Wrap = wdFindStop
.MatchWildcards = True
.Text = "[^13]{1,}"
.Replacement.Text = ""
.Execute Replace:=wdReplaceAll
End With
Next
Application.ScreenUpdating = True
End Sub

Visual Basic edit Word documents in bulk

I have hundreds of docx-documents which I would like to edit in bulk with a visual basic macro. They all share an id on the first line which looks like this:
9-ZKB-S
Or
12-JK-17
I would like to remove the '-' from the id so it will become like this:
9ZKBS
Or
12JK17
Then somewhere in the document I have a word followed by a number like this:
Productionnumber. 42-563-12
And I also would like to remove the minus character:
Productionnumber. 4256312
I've found a visual basic script which enables me to select a folder containing word-documents and to perform a search and replace. But I don't know how to do the specific things I've mentioned such as:
In each document, remove the - and the space between characters on the first line
In each document, remove the - and the space between characters after Productionnumber.
Sub CommandButton1_Click()
Dim MyDialog As FileDialog, GetStr(1 To 500) As String '100 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 ", "*.docx", 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 = "search" 'Find What
.Replacement.Text = "find" '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"
ActiveDocument.Save
ActiveWindow.Close
Next
Application.ScreenUpdating = True
End With
MsgBox "operation end, please view", vbInformation
End Sub
Look into Using wildcards and test the pattern in word first. For example (not tested):
With Doc.Range.Find
.MatchWildcards = True
.Text = "<(?*)>\-<(?*)>\-<(?*)>"
.Replacement.Text = "\1\2\3" 'Replace With
' ... the rest of the options
End With

How to modify this VBA code for VB

I am using this VBA code for covnvert textbox text to regular text. But its through errors on shp.Type and sString = Left(shp.TextFrame.TextRange.Text, _
shp.TextFrame.TextRange.Characters.Count - 1), while i am compiling in VB.
What should i change in the code for VB?
This is VBA code:
Sub ConvertTextBoxToText()
Dim shp As Shape
Dim oRngAnchor As Range
Dim sString As String
For Each shp In ActiveDocument.Shapes
If shp.Type = msoTextBox Then
' copy text to string, without last paragraph mark
sString = Left(shp.TextFrame.TextRange.Text, _
shp.TextFrame.TextRange.Characters.Count - 1)
If Len(sString) > 0 Then
' set the range to insert the text
Set oRngAnchor = shp.Anchor.Paragraphs(1).Range
' insert the textbox text before the range object
oRngAnchor.InsertBefore sString
End If
shp.Delete
End If
Next shp
'Strip out beginning and ending textbox markers
Selection.HomeKey unit:=wdStory
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
With Selection.Find
.Text = "Textbox start << "
.Replacement.Text = ""
.Forward = True
' .Wrap = wdFindContinue
.Format = False
.MatchCase = True
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Selection.Find.Execute Replace:=wdReplaceAll
With Selection.Find
.Text = ">> Textbox end"
.Replacement.Text = ""
.Forward = True
.wrap = wdFindContinue
.Format = False
.MatchCase = True
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Selection.Find.Execute Replace:=wdReplaceAll
End Sub
VB Code:?
Could you please?
VB uses VBA as it's language. So no conversion needed. VB is an app object and forms package that hosts VBA, like Word is a Word Processor that hosts VBA.
In your code you don't connect to Word. In Word, some objects are made automatically available. Outside of Word you have to connect to them.
Set xlBook = GetObject("C:\Users\User\Documents\Super.xls")
For each wsheet in xlbook.worksheets
msgbox wsheet.name
wsheet.printOut
next
or
set xlapp = createobject("Excel.Application")
xlapp.Workbooks.Open "C:\Users\User\Documents\Super.xls"
'43 is 95/97 look up xlExcel9795 in object browser to see other options
xlapp.ActiveWorkbook.SaveAs "C:\Users\User\Documents\Super.xls", 43
or
Set GetExcelApp = GetObject("", "Excel.Application")
Msgbox GetExcelApp