VBA find and replace in a word doc's footer - excel

I have a document that has a bunch of <<system>> in its footers.
So far I've just been highlighting them and pasting over, which is very tedious.
I would like VBA to do this for me.
I have a macro written that takes care of all the find and replaces in the document, except it isn't working in the footers.
Looking on google, it seems that all I'm finding is how to do it with the vba in word, but I need to work from vba in excel. Is it possible to make it work from there?
vba used (works for everything in the word doc except the stuff in the footers):
Dim objword
Set objword = GetObject(, "Word.Application")
With objword.ActiveDocument.Content
With .Find
.Execute FindText:="thing to search", ReplaceWith:="thing to replace", Replace:=1 '(or 2)
End With
End With

Life is a lot easier if you add a reference to Word objects in Excel, but otherwise, this might work from Excel:
Public Sub UpdateWord()
Dim wrdObj As Object ' Application object
Dim wrdDoc As Object ' Word object
Dim sect As Object ' Section
Dim footr As Object ' Footer
Dim sel As Object ' Selection
Dim kwrd_find As String: kwrd_find = "<<system>>" ''' Keyword to find
Dim kwrd_replace As String: kwrd_replace = "Hello" ''' Word to replace keyword
Dim DocPath As String: DocPath = "C:\path\to\my\word-document.docx"
Set wrdObj = GetObject(, "Word.Application")
''' Open word document
''' Change `Visible` to False if you don't want to see it.
Set wrdDoc = wrdObj.Documents.Open(DocPath, ReadOnly:=False, Visible:=True)
On Error Resume Next
With wrdDoc
''' Run through all sections and footers (you can add headers, too).
For Each sect In .Sections
For Each footr In sect.Footers
With footr.Range.Find
.Text = kwrd_find ''' Keyword to find
.Replacement.Text = kwrd_replace ''' Word to replace keyword
.Wrap = wdFindContinue ''' Wrap it up.
Call .Execute(Replace:=wdReplaceAll)
End With
Next
Next sect
End With
''' Close and save document
Call wrdDoc.Close(SaveChanges:=True)
''' Clean up e'rything.
Set wrdDoc = Nothing
Set wrdObj = Nothing
End Sub

Related

Find and copying text highlighted in a specific color

Hi I have a code (see below) that is working like a charm to find and copy text from a specific style and paste it in another document. It is in an excel file because I preferred this option to share with friends that would only need to click in the button, chose the input file and save as their preferred output file name.
Now I'm trying without success to perform the same task with text highlighted in a specific color (e. Turquoise). Please find below the code that is working with a specific word or style, I made some experiences with code I found here and there, but all I could get was to copy all highlighted text instead of my choice of color. See below. Any help is much appreciated.
Note on Edit: The code below is the closer I get to the desired result. It was a little chaotic due to my try and error attempts.
' Objects
Dim wrdApp, objWord As Object
Dim wrdDoc, newwrdDoc As Object
Dim myPath As String, myPath1 As String
Dim folderPath As String
Dim myFile As String
Dim numberStart As Long
Dim Rng, srchRng As Excel.Range
'Dim objDoc As Document, objDocAdd As Document
Dim objRange As Range
Dim strFindColor As String
Dim highliteColor As Variant
Dim i As Long
' Close MS Word if it's already opened
On Error Resume Next
Set objWord = GetObject(, "Word.Application")
If Not objWord Is Nothing Then
objWord.Quit SaveChanges:=0
Set objWord = Nothing
End If
'Defining input file name
myFile = Application.GetOpenFilename()
'Open MS Word
Set wrdApp = CreateObject("Word.Application")
wrdApp.Visible = True
' Folder Location
myPath = Application.ThisWorkbook.Path & "\"
' Input File
Set wrdDoc = wrdApp.Documents.Open(myFile)
' Output File
Set newwrdDoc = wrdApp.Documents.Add
myPath1 = Application.GetSaveAsFilename(FileFilter:="Word files(*.docx),*.docx")
' Text you want to search
'Dim FindWord As String
'Dim result As String
'FindWord = ""
highliteColor = Array(wdTurquoise)
'Style
'mystyle = wdTurquoise
'Defines selection for Word's find function
wrdDoc.SelectAllEditableRanges
' Find Functionality in MS Word
For i = LBound(wdTurquoise) To UBound(wdTurquoise)
objDoc.Activate
Selection.HomeKey Unit:=wdStory
objRange.Collapse wdCollapseEnd
With wrdDoc.ActiveWindow.Selection.Find
.HighlightColorIndex = wdTurquoise
.Highlight = True
.Forward = True
.Wrap = wdFindStop
objRange = Selection.Range
objDocAdd.Range.InsertAfter objRange & vbCr
Selection.Collapse wdCollapseEnd
End With
Next
' Execute find method
wrdDoc.ActiveWindow.Selection.Find.Execute
' Store Selected text
result = wrdDoc.ActiveWindow.Selection.Text
' Check if result contains non-blank text
If Len(result) > 1 Then
' -------------------------------------------------------------
' Loop through multiple find content (Find All functionality)
' -------------------------------------------------------------
While wrdDoc.ActiveWindow.Selection.Find.Found
wrdDoc.ActiveWindow.Selection.Copy
'Activate the new document
newwrdDoc.Activate
'New Word Doc
Set Rng = newwrdDoc.Content
Rng.Collapse Direction:=wdCollapseEnd
Rng.Paste
'Word Document
wrdDoc.Activate
wrdDoc.ActiveWindow.Selection.Find.Execute
Wend
' If style not found
Else
MsgBox "Text Not Found"
End If
'Close and don't save application
wrdDoc.Close SaveChanges:=False
'Save As New Word Document
newwrdDoc.SaveAs myPath1
newwrdDoc.Close SaveChanges:=True
'Close all word documents
wrdApp.Quit SaveChanges:=0
'Message when done
MsgBox "Task Accomplished"
End Sub

Find and Replace footer text in Word with an Excel VBA Macro

I'm trying to make a macro in Excel which opens a Word document, find a especify text, which is inside of footer in word doc, and replace it for a text.
At the moment, my macro opens the word doc but I couldn't figure out how to get into footer and find those texts.
Dim objWord
Dim objDoc
Set objWord = CreateObject("Word.Application")
Set objDoc = objWord.Documents.Open(ThisWorkbook.Path & "/NotaPromissoriaAutomatica.docx")
objWord.Visible = True
The footer have two texts which have to be replaced
1 - VAR_CIDADE > Which will be replaced the current city (which is in A1 of my excel table)
2 - VAR_DATA > Which will be replaced the current date (which is in A2 of my excel table)
I created a test document with a single page, header and footer, with the footer using the keyword "VAR_DATA". The example code below will search for all footers in the document and make the replacement. Notice that the code only searches in Section(1) though. If you have more sections, you may have to create an outer loop to search for each footer in every section.
Option Explicit
Public Sub FixMyFooter()
Dim myWord As Object
Dim myDoc As Word.Document
Set myWord = CreateObject("Word.Application")
Set myDoc = myWord.Documents.Open("C:\Temp\footertest.docx")
Dim footr As Word.HeaderFooter
For Each footr In myDoc.Sections(1).Footers
With footr.Range.Find
.Text = "VAR_DATA"
.Replacement.Text = Format(Now(), "dd-mmm-yyyy")
.Execute Replace:=wdReplaceAll, Forward:=True, Wrap:=wdFindStop
End With
Next footr
myDoc.Save
myWord.Quit
End Sub
You'll need to expand the example to find your additional text with your own formatting.

Finding heading of chapters in word file and copying individual paragraphs to new word file with VBA

Since nobody was able to help me with the problem I posted here before (link is below), I am now trying to solve the task through VBA.
Finding a heading in word file and copying entire paragraph thereafter to new word file with python
To briefly recap, I have a large amount of word files, which I would like to reduce to a more readable size each. In each file, there is one heading that appears several times, always formated as a 'Heading 2'. I look for this specific heading which occurs several times in a document and I want to copy all the text parts in just these chapters with the respective heading to a new word document.
I decided to create an excel file in which I list the files and the respective heading of the chapters that I want to copy (see picture below).
To do this now I have written the following code:
Sub SelectData()
Application.ScreenUpdating = False
Dim WdApp As Word.Application
Set WdApp = CreateObject("Word.Application")
Dim Doc As Word.Document
Dim NewDoc As Word.Document
Dim HeadingToFind As String
Dim ChapterToFind As String
Dim StartRange As Long
Dim EndRange As Long
Dim WkSht As Worksheet
Dim LRow As Long
Dim i As Long
Set WkSht = ThisWorkbook.Sheets("Sheet1")
LRow = WkSht.UsedRange.Cells.SpecialCells(xlCellTypeLastCell).Row
With WkSht
For i = 1 To LRow
If Dir(.Cells(i, 1).Text, vbNormal) = "" Then
.Cells(i, 3).Value = "Please check File Location"
Else
Set Doc = WdApp.Documents.Open(Filename:=.Cells(i, 1).Text, _
AddToRecentFiles:=False, Visible:=False, ReadOnly:=False)
Set NewDoc = Documents.Add
ChapterToFind = LCase(.Cells(i, 2).Text)
With Doc
Selection.HomeKey Unit:=wdStory
With Selection
With .Find
.ClearFormatting
.Text = ChapterToFind
.MatchWildcards = False
.MatchCase = True
.Execute
End With
If .Find.Found Then
.Collapse wdCollapseStart
With .Find
.Text = ""
.Style = "Heading 2"
.Forward = False
.Execute
End With
.MoveDown Count:=1
.HomeKey Unit:=wdLine
StartRange = .Start
.Find.Forward = True
.Find.Execute
.Collapse wdCollapseStart
.MoveUp Count:=1
.EndKey Unit:=wdLine
EndRange = .End
Doc.Range(StartRange, EndRange).Copy
NewDoc.Content.Paste
NewDoc.SaveAs2 Doc.Path & "Clean" & ".docx", wdFormatFlatXML
Else
WkSht.Cells(i, 4).Value = "Error Chapter Not Found"
End If
End With
End With
WdApp.Quit
Set Doc = Nothing: Set NewDoc = Nothing: Set WdApp = Nothing: Set WkSht = Nothing
Application.ScreenUpdating = True
End If
Next
End With
End Sub
However I am really struggling. It seems to not work as I constantly get an error with the command (RunTimeError 438):
Selection.HomeKey Unit:=wdStory
I am aware that I have to activate the Microsoft Word 15.0 Object Library in the references to be able to get word commands. Nevertheless it is not working.
I would greatly appreciate any help, I am also open to other suggestions of course.
The word files look something like in the picture below, however the chapter that I want to extract can occur several times within one word document. As a result my code would probably need a loop or something, I was not able to get this done.
Also I have considered the following links to the topic:
Use VBA with Powerpoint to Search titles in a Word Doc and Copy Text into another Word Document
VBA: open word from excel
word vba: select text between headings
Did I understand this correctly? The following code is the core of what I think you're trying to do. It finds the first Heading 2, then finds all the paragraphs after it until it finds another header of any type or the end of the document. startCopyRange and endCopyRange is the range of those paragraphs. You'll have to piece this into your Excel routine.
A few notes. Always save the active document to a variable and work from that; the user is then free to change active documents while this routine is running. Never use Selection, always use ranges. Never use relative movements like Move, always use API calls.
Sub SelectData()
Dim Doc As Word.Document
Set Doc = ActiveDocument
Dim findRange As Range
Set findRange = Doc.Range
ChapterToFind = "My Chapter"
findRange.Find.Text = ChapterToFind
findRange.Find.Style = "Heading 2"
findRange.Find.MatchCase = True
Dim startCopyRange As Long
Dim endCopyRange As Long
Do While findRange.Find.Execute() = True
startCopyRange = findRange.End + 1
endCopyRange = -1
'findRange.Select
Dim myParagraph As Paragraph
Set myParagraph = findRange.Paragraphs(1).Next
Do While Not myParagraph Is Nothing
myParagraph.Range.Select 'Debug only
If InStr(myParagraph.Style, "Heading") > 0 Then
endCopyRange = myParagraph.Range.Start - 0
End If
If myParagraph.Next Is Nothing Then
endCopyRange = myParagraph.Range.End - 0
End If
If endCopyRange <> -1 Then
Doc.Range(startCopyRange, endCopyRange).Select 'Debug only
DoEvents
Exit Do
End If
Set myParagraph = myParagraph.Next
DoEvents
Loop
Loop
End Sub

Excel VBA - Cross Referencing Bookmark/Form Field to Word

I have very minimal knowledge about VBA but still learning as it goes.
I've been using bookmarks in the word in order to populate data from excel. However, due to the content that some data need to repeat in a document, I tried using Text Form Field/Bookmark and REF Field to duplicate the same data.
The problem came in when once I populated data to the word, the text form field/bookmark disappear which causes REF Field unable to track the data that was referred to, hence, the "Error! Reference source not found."
In conclusion, what I'm trying to do is to populate data from excel to a locked word document and at the same time to retain Text Field Form/Bookmark in order to let REF field to track and duplicate the same data.
Is there any way to retain the Text Field Form/Bookmark placeholder after data is populated to the word? Here's my code that I am unable to solve in excel VBA.
Appreciate your help in advance!
Private Sub CommandButton1_Click()
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets("Sheet1")
Dim objWord As Object
Set objWord = CreateObject("Word.Application")
objWord.Visible = True
objWord.Documents.Open "C:\Users\" & Environ("username") & "\Desktop\XXX\XXX"
objWord.ActiveDocument.Unprotect Password:="xxx"
With objWord.ActiveDocument
Dim objBMRange As Range
Set objBMRange = .Bookmarks("pr1").Range.Text = ws.Range("C28").Value
objBMRange.Text = pr1
.Bookmarks.Add "pr1", BMRange
.Fields.Update
objWord.ActiveDocument.Protect Password:="xxx", NoReset:=False, Type:=wdAllowOnlyFormFields
End With
Set objWord = Nothing
End Sub
You were almost there. Very near, but you didn't get the Range object sorted out. Please try this code (only partially tested).
Private Sub CommandButton1_Click()
Dim Ws As Worksheet
Dim objWord As Object
Dim Mark As String
Dim Txt As String
Dim BmkStart As Long
Mark = "pr1"
Set Ws = ThisWorkbook.Sheets("Sheet1")
Txt = Ws.Range("C28").Value
Set objWord = CreateObject("Word.Application")
With objWord
.Visible = True
.Documents.Open "C:\Users\" & Environ("username") & "\Desktop\XXX\XXX"
With .ActiveDocument
.Unprotect Password:="xxx"
If .Bookmarks.Exists(Mark) Then
With .Bookmarks(Mark).Range
BmkStart = .Start
.Text = Txt
End With
.Bookmarks.Add Mark, .Range(BmkStart, BmkStart + Len(Txt))
End If
.Fields.Update
.Protect Password:="xxx", NoReset:=False, Type:=wdAllowOnlyFormFields
End With
End With
Set objWord = Nothing
End Sub
One point is that the Bookmark defines a Word.Range (different from an Excel.Range which you get when you specify no application while working in Excel). The other, that Bookmark defines a range but isn't a range itself, not even a Word.Range. Therefore you get or set its text by modifying it's range's Text property.

Loop through Excel rows, key in on value in Word, paste Excel string

I am trying to loop through Excel rows, where column A holds text that I want to find in Word. Column B holds what I want to paste in Word after the end of the paragraph in which the text is found.
When working in Word VBA, the find text is working and moving to the end of the paragraph works. But when I move to Excel VBA, the find method doesn't seem to be doing anything.
Sub UpdateWordDoc1()
Dim mywb As Excel.Worksheet
Set mywb = ActiveWorkbook.ActiveSheet
Dim wdDoc As Object, wdApp As Object
Dim questiontext As String
Dim oSearchRange
On Error Resume Next
Set wdDoc = CreateObject("C:\mydoc.docx")
Set wdApp = wdDoc.Application
Set oSearchRange = wdDoc.Content
With mywb
For i = 2 To .Range("A6000").End(xlUp).Row
questiontext = .Range("A" & i).Value
.Range("B" & i).Copy
Set blabla = oSearchRange.Find.Execute.Text = questiontext
blabla.Select
Selection.movedown unit:=wdparagraph
Selection.moveleft unit:=wdcharacter
Selection.PasteAndFormat (wdFormatOriginalFormatting)
Next i
End With
'wdDoc.Close savechanges:=True
Set wdDoc = Nothing
Set wdApp = Nothing
End Sub
I think this code does what you're after. I made a number of small changes to the code in the original post, some important, some not so much. Hopefully the comments help explain why I did what I did:
Sub UpdateWordDoc1()
' REQUIRES A REFERENCE TO:
' Microsoft Word ##.# Object Library
Dim myws As Excel.Worksheet ' Changed wb to ws to better abbreviate worksheet
Dim wdDoc As Word.Document ' No longer a generic object
Dim wdApp As Word.Application ' No longer a generic object
Dim questiontext As String
Dim oSearchRange As Word.Range ' Word range is what will be searched
Dim i As Long ' Loop through rows by count (Long)
Set myws = ActiveWorkbook.ActiveSheet
' On Error Resume Next ' Can't find bugs if they're supressed!!!
Set wdApp = CreateObject("Word.Application") ' Create app before opening doc
' Need to explore what happens
' if Word is already running
wdApp.Visible = True ' Make it visible so we can watch it work
Set wdDoc = wdApp.Documents.Open("C:\mydoc.docx") ' Open the doc
With myws
For i = 2 To .Range("A6000").End(xlUp).Row
' Word's Find function is tricky to program, because
' when Find succeeds, the range is moved! (Find has many
' other odd behaviors). Assuming you want to search the entire doc
' for each search term, we reset the range every time through the
' loop.
Set oSearchRange = wdDoc.Content
questiontext = .Range("A" & i).Value
.Range("B" & i).Copy
' Set blabla = oSearchRange.Find.Execute.Text = questiontext
With oSearchRange.Find
' Note that Word's Find settings are "sticky". For example, if
' you were previously searching for (say) italic text before
' running this Sub, Word may still search for italic, and your
' search could fail. To kill such bugs, explicitly set all of
' Word's Find parameters, not just .Text
.Text = questiontext ' This is what you're searching for
If .Execute Then ' Found it.
' NOTE: This is only gonna make a change
' at the first occurence of questiontext
' When find is successful, oSearchRange will move
' to the found text. But not the selection, so do Select.
oSearchRange.Select
' Now move to where the new text is to be pasted
wdDoc.ActiveWindow.Selection.movedown unit:=wdparagraph
wdDoc.ActiveWindow.Selection.moveleft unit:=wdcharacter
' While debugging, the next statement through me out of single
' step mode (don't know why) but execution continued
' and the remaining words in my list we're found and text
' pasted in as expected.
wdDoc.ActiveWindow.Selection.PasteAndFormat (wdFormatOriginalFormatting)
End If
End With
Next i
End With
' Clean up and close down
wdDoc.Close savechanges:=True
Set oSearchRange = Nothing
Set wdDoc = Nothing
wdApp.Quit
Set wdApp = Nothing
Set myws = Nothing
End Sub
Hope that helps

Resources