Replace datefields in a document - vba

I want to replace all date fields with, for example, "hello".
This Word VBA code replaces all the fields in the header and footer of the document. I only want to replaces the date fields.
Sub test()
Dim oField As Field
Dim oSection As Section
Dim oHeader As HeaderFooter
Dim oFooter As HeaderFooter
For Each oSection In ActiveDocument.Sections
For Each oHeader In oSection.Headers
If oHeader.Exists Then
For Each oField In oHeader.Range.Fields
If oField = wdFieldDate Then
oField.Result.Text = "hello"
oField.Unlink
Else
End If
Next oField
End If
Next oHeader
For Each oFooter In oSection.Footers
If oFooter.Exists = True Then
For Each oField In oFooter.Range.Fields
If IsDate(oField) = True Then
oField.Result.Text = "hello"
oField.Unlink
Else
End If
Next oField
End If
Next oFooter
Next oSection
End Sub

In your cross-post, you specified that you wanted DATE and TIME fields.
Sub DateFieldsReplace()
' Replace any date fields in active document
' Charles Kenyon 2020-09-09
' https://answers.microsoft.com/de-de/msoffice/forum/all/word-macro-search-for-date-fields-and-replace/ad578c92-e1ce-4258-903f-552dfae2a843
' =====================================================
' DECLARE VARIABLES AND CONSTANTS
Dim oField As Field, bErrMark As Boolean, strPrompt As String, bFieldCodeHidden As Boolean
Dim oStory As Range
Const strREPLACETEXT = "Hello" ' Change to suit
'
' =====================================================
' TURN OFF SCREEN UPDATING
' Application.ScreenUpdating = False
On Error GoTo OOPS
Let bFieldCodeHidden = ActiveWindow.View.ShowFieldCodes ' get current setting for field code display
Let ActiveWindow.View.ShowFieldCodes = True
'
' =====================================================
' FIND AND REPLACE DATE FIELDS
For Each oStory In ActiveDocument.StoryRanges
With oStory.Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = "^d Date"
.Replacement.Text = strREPLACETEXT
.Execute Replace:=wdReplaceAll
.Text = "^d Time"
.Execute Replace:=wdReplaceAll
End With
Next oStory
'
Let strPrompt = "All Date fields replaced with " & strREPLACETEXT
GoTo ResumeMacro
' =====================================================
' ERROR HANDLER
OOPS:
Let strPrompt = "Sorry. There was a problem with the macro DateFieldsReplace."
'
ResumeMacro:
'
' =====================================================
' RETURN SCREEN UPDATING AND FINISH
With ActiveDocument.Range.Find
.ClearFormatting
.Text = ""
.Replacement.ClearFormatting
.Replacement.Text = ""
End With
Application.ScreenUpdating = True
Application.ScreenRefresh
Set oField = Nothing
Set oStory = Nothing
Let ActiveWindow.View.ShowFieldCodes = bFieldCodeHidden
On Error GoTo -1
MsgBox strPrompt
'
End Sub
A document with this code can be found at this temporary link.
For cross-posting etiquette, please please read: A Message to Forum Cross-Posters

If oField = wdFieldDate Then doesn't compile because you haven't specified which property of the field you want to check. Your code should be as below
Sub test()
Dim oField As Field
Dim oSection As Section
Dim oHeader As HeaderFooter
Dim oFooter As HeaderFooter
For Each oSection In ActiveDocument.Sections
For Each oHeader In oSection.Headers
If oHeader.Exists Then
For Each oField In oHeader.Range.Fields
'check the field type
If oField.Type = wdFieldDate Then
oField.Result.Text = "hello"
oField.Unlink
Else
End If
Next oField
End If
Next oHeader
For Each oFooter In oSection.Footers
If oFooter.Exists = True Then
For Each oField In oFooter.Range.Fields
If oField.Type = wdFieldDate Then
oField.Result.Text = "hello"
oField.Unlink
Else
End If
Next oField
End If
Next oFooter
Next oSection
End Sub

Related

Add start and end word fields for tracked changes

I want to add two word fields at the start and end of each track change of a document.
I am iterating through the word revisions using a for-each loop.
Below is my code :
Private Function TrackChangesOnDeletions(ByRef WordRange As Word.Range)
On Error GoTo ErrorHandler
Dim fTrackRevisions As Boolean
Dim objRevision As Word.Revision
Dim objContentControl As Word.ContentControl
Dim objRange As Word.Range
Dim objField As Word.Field
Dim index As Long
Dim objRangeCopy As Word.Range
Dim objFieldEnd As Word.Field
With WordRange.Document
fTrackRevisions = .TrackRevisions
.TrackRevisions = False
End With
With WordRange
For Each objRevision In .Revisions
On Error Resume Next
With objRevision
Set objRange = .Range
'Make sure there's no break character that may exist at the end of the specified range,
'in order to avoid end field appears at the beginning of the next line.
If Len(.Range.Text) > 0 Then
Select Case Asc(WordRange.Characters.Last)
Case 7, 10, 11, 12, 13, 14
.Range.MoveEnd Unit:=WdUnits.wdCharacter, Count:=-1
End Select
End If
'Create a copy of the passed range.
Set objRangeCopy = .Range.Duplicate
With objRangeCopy
.Collapse wdCollapseEnd
'Ensure we are not at an end-of-row marker.
Do While .Information(wdAtEndOfRowMarker) = True
.MoveEnd Unit:=WdUnits.wdCharacter, Count:=1
.Collapse wdCollapseEnd
Loop
End With
'Create a new field at the specified range.
Set objFieldEnd = objRangeCopy.Fields.Add(Range:=objRangeCopy, Type:=wdFieldComments, PreserveFormatting:=False)
'Insert end tag
objFieldEnd.Code.InsertAfter " >"
Set objRangeCopy = .Range.Duplicate
objRangeCopy.Collapse Direction:=wdCollapseStart
objFieldEnd.Update
'Insert the start tag
Set objField = objRangeCopy.Fields.Add(Range:=objRangeCopy, Type:=wdFieldComments, Text:="Deletion< ", PreserveFormatting:=False)
objField.Update
objRange.SetRange Start:=objField.Code.Start - 1, End:=objFieldEnd.Code.End + 3
objRange.Font.StrikeThrough = True
objRange.Font.ColorIndex = wdRed
.Reject
End With
Err.Clear
Set objContentControl = Nothing
Next objRevision
End With
ErrorHandler:
WordRange.Document.TrackRevisions = fTrackRevisions
Set objContentControl = Nothing
Set objField = Nothing
Set objRange = Nothing
Set objRevision = Nothing
Select Case Err.Number
Case 0
Case Else
ShowUnexpectedError ErrorSource:="TrackChangesOnDeletions" & vbCr & Err.Source
End Select
End Function
My issue is, once the code executed for the first revision, it gets the first revision as the next revision (at for loops' next) as well, event the revision count remain same. So the start and end fields keep adding to the first revision and it makes word crash.
For the below original text,
I need the output as,
When the field codes are hidden, it should display as :
But my code gives the output as, (I have manually stop the for loop iteration to have this capture, else it will add fields and fields and cause word crash)
Form my further testings, I have identified that, if some text were inserted before the revision within the loop, the next revision will be same as the current revision. So the loop is running nonstop and then crash word.
Could anybody please tell me what I am doing wrong here.
Thank you in advance.
In order to move out from the loop at correct time, I used the below approach.
Any improvements or other answers are appreciated.
Private Function TrackChangesOnDeletions(ByRef WordRange As Word.Range)
On Error GoTo ErrorHandler
Dim fTrackRevisions As Boolean
Dim objRevision As Word.Revision
Dim objRange As Word.Range
Dim objRangeCopy As Word.Range
Dim objFieldStart As Word.Field
Dim objFieldEnd As Word.Field
Dim index As Long
Dim revisionCount As Long
With WordRange.Document
fTrackRevisions = .TrackRevisions
.TrackRevisions = False
End With
revisionCount = WordRange.Revisions.Count
index = 1
If (revisionCount > 0) Then
Set objRevision = WordRange.Revisions(index)
Do While Not objRevision Is Nothing
If AllowTrackChangesForDeletion(objRevision) = True Then
On Error Resume Next
With objRevision
Set objRange = .Range
'Make sure there's no break character that may exist at the end of the specified range,
'in order to avoid end field appears at the beginning of the next line.
If Len(objRange.Text) > 0 Then
Select Case Asc(objRange.Characters.Last)
Case 7, 10, 11, 12, 13, 14
objRange.MoveEnd Unit:=WdUnits.wdCharacter, Count:=-1
End Select
End If
'Create a copy of the passed range.
Set objRangeCopy = objRange.Duplicate
With objRangeCopy
.Collapse wdCollapseEnd
'Ensure we are not at an end-of-row marker.
Do While .Information(wdAtEndOfRowMarker) = True
.MoveEnd Unit:=WdUnits.wdCharacter, Count:=1
.Collapse wdCollapseEnd
Loop
End With
'Create a new field at the specified range.
Set objFieldEnd = objRangeCopy.Fields.Add(Range:=objRangeCopy, Type:=wdFieldComments, PreserveFormatting:=False)
'Insert end tag
objFieldEnd.Code.InsertAfter " >"
Set objRangeCopy = objRange.Duplicate
objRangeCopy.Collapse Direction:=wdCollapseStart
objFieldEnd.Update
'Insert the start tag
Set objFieldStart = objRangeCopy.Fields.Add(Range:=objRangeCopy, Type:=wdFieldComments, Text:="Deletion< ", PreserveFormatting:=False)
objFieldStart.Update
objRange.SetRange Start:=objFieldStart.Code.Start - 1, End:=objFieldEnd.Code.End + 3
objRange.Font.StrikeThrough = True
objRange.Font.ColorIndex = wdRed
.Reject
End With
Err.Clear
End If
'Move to the next revision (unable to use for loop, because it iterates through the first revision everytime and
'then crash word
index = index + 1
If index > revisionCount Then
Exit Do
End If
Set objRevision = WordRange.Revisions(index)
Loop
End If
ErrorHandler:
WordRange.Document.TrackRevisions = fTrackRevisions
Set objFieldEnd = Nothing
Set objFieldStart = Nothing
Set objRange = Nothing
Set objRangeCopy = Nothing
Set objRevision = Nothing
Select Case Err.Number
Case 0
Case Else
ShowUnexpectedError ErrorSource:="TrackChangesOnDeletions" & vbCr & Err.Source
End Select
End Function

Using VBA code how to extract Non HTML data content residing under each heading from a word document

How to extract text and non text data content (ex: Tables, pictures) associated with each heading irrespective of heading style?
With below code I am able to reach out to each header, post that I am failing to extract content associated with that heading:
Option Explicit
Sub Main()
Dim strFile As String
Dim oWord As Word.Application
Dim oWdoc As Word.Document
Dim oPar As Word.Paragraph
Dim rng As Word.Range
strFile = "C:\Users\SQVA\Desktop\My_Work\MyTest3.docx"
'Set oWord = CreateObject("Word.Application")
Set oWord = New Word.Application
Set oWdoc = oWord.Documents.Open(strFile)
Call Get_Heading_Name(oWord, oWdoc, strFile, rng)
Call Close_Word(oWord, oWdoc)
End Sub
Sub Get_Heading_Name(oWord As Word.Application, oWdoc As Word.Document, strFile As String, rng As Word.Range)
oWord.Visible = True
Dim astrHeadings As Variant
Dim strText As String
Dim intItem As Integer
Set rng = oWdoc.Content
astrHeadings = _
oWdoc.GetCrossReferenceItems(wdRefTypeHeading)
For intItem = LBound(astrHeadings) To UBound(astrHeadings)
strText = Trim$(astrHeadings(intItem))
'Debug.Print CStr(strText)
'Debug.Print astrHeadings(intItem).
Dim my_String As String
Dim intLevel
If CStr(strText) <> "" Then
my_String = Right(strText, Len(strText) - InStr(strText, " "))
intLevel = GetLevel(CStr(astrHeadings(intItem)))
' Call GetHeadingNextText(oWdoc, my_String)
' Debug.Print my_String
' Debug.Print intLevel
' rng.Style = "Heading " & intLevel
Dim sTextSearch() As String
Dim StrHdTxt1
Dim nStart As Long, nEnd As Long, n As Long, k As Long
Dim wdTable
Dim wdTbl As Word.Table, wdCell As Word.cell, wdCellRng As Word.Range
Dim wdIshp As Word.InlineShape, wdShp As Word.Shape, StrHdTxt As String
oWdoc.Range(0, 0).Select
With oWord.Selection.Find
.Style = oWdoc.Styles("Heading " & intLevel)
.Text = my_String
If .Execute Then
'Debug.Print "Found"
Call SelectHeadingandContent(oWdoc, oWord)
End If
End With
End If
Next intItem
End Sub
Sub Close_Word(oWord As Word.Application, oWdoc As Word.Document)
oWdoc.Close SaveChanges:=wdDoNotSaveChanges
oWord.Quit
Set oWdoc = Nothing
Set oWord = Nothing
End Sub
Private Function GetLevel(strItem As String) As Integer
' Return the heading level of a header from the
' array returned by Word.
' The number of leading spaces indicates the
' outline level (2 spaces per level: H1 has
' 0 spaces, H2 has 2 spaces, H3 has 4 spaces.
Dim strTemp As String
Dim strOriginal As String
Dim longDiff As Integer
' Get rid of all trailing spaces.
strOriginal = RTrim$(strItem)
' Trim leading spaces, and then compare with
' the original.
strTemp = LTrim$(strOriginal)
' Subtract to find the number of
' leading spaces in the original string.
longDiff = Len(strOriginal) - Len(strTemp)
GetLevel = (longDiff / 2) + 1
End Function
Sub SelectHeadingandContent(oWdoc As Word.Document, oWord As Word.Application)
Dim headStyle 'As Style
' Checks that you have selected a heading. If you have selected multiple paragraphs,checks only the first one. If you have selected a heading, makes sure the whole paragraph is selected and records the style. If not, exits the subroutine.
If oWdoc.Styles(oWord.Selection.Paragraphs(1).Style).ParagraphFormat.OutlineLevel < wdOutlineLevelBodyText Then
Set headStyle = oWord.Selection.Paragraphs(oWord.Selection.Paragraphs.Count).Style
oWord.Selection.Expand wdParagraph
Else: Exit Sub
End If
' Turns off screen updating so the the screen does not flicker.
Application.ScreenUpdating = False
' Loops through the paragraphs following your selection, and incorporates them into the selection as long as they have a higher outline level than the selected heading (which corresponds to a lower position in the document hierarchy). Exits the loop if there are no more paragraphs in the document.
Dim My_Text As String
My_Text = ""
Do While oWdoc.Styles(oWord.Selection.Paragraphs(oWord.Selection.Paragraphs.Count).Next.Style).ParagraphFormat.OutlineLevel > headStyle.ParagraphFormat.OutlineLevel
'Debug.Print oWord.Selection.Paragraphs(oWord.Selection.Paragraphs.Count).Range.Text
oWord.Selection.MoveEnd wdParagraph
' Debug.Print oWord.Selection.Paragraphs(oWord.Selection.Paragraphs.Count).Range.Text
My_Text = My_Text + vbCr + oWord.Selection.Paragraphs(oWord.Selection.Paragraphs.Count).Range.Text
If oWord.Selection.Paragraphs(oWord.Selection.Paragraphs.Count).Next Is Nothing Then Exit Do
Loop
Debug.Print My_Text
' Turns screen updating back on.
Application.ScreenUpdating = True
End Sub
You can loop through all the Heading1 ranges and their 'non-text' objects, as you call them, with code like:
Sub Read_Heading_Contents()
Dim wdApp As New Word.Application, wdDoc As Word.Document, wdRng As Word.Range
Dim wdTbl As Word.Table, wdCell As Word.Cell, wdCellRng As Word.Range
Dim wdIshp As Word.InlineShape, wdShp As Word.Shape, StrHdTxt As String
Const strFile As String = "C:\Users\SQVA\Desktop\My_Work\MyTest3.docx"
With wdApp
.Visible = True
Set wdDoc = .Documents.Open(Filename:=strFile, ReadOnly:=True, AddToRecentFiles:=False, Visible:=False)
With wdDoc
With .Range
With .Find
.Style = wdStyleHeading1
.Text = ""
.Wrap = wdFindStop
.Execute
End With
If .Find.Found = False Then
MsgBox "No 'Heading 1' style found."
Else
Do While .Find.Found = True
StrHdTxt = .Duplicate.Text: MsgBox StrHdTxt
Set wdRng = .Duplicate.GoTo(What:=wdGoToBookmark, Name:="\HeadingLevel")
For Each wdTable In .Tables
With wdTbl
For Each wdCell In .Range.Cells
Set wdCellRng = wdCell.Range
wdCellRng.End = wdCellRng.End - 1
MsgBox wdCellRng.Text
Next
End With
Next
For Each wdIshp In wdRng.InlineShapes
With wdIshp
If Not .TextEffect Is Nothing Then
MsgBox .TextEffect.Text
End If
End With
Next
For Each wdShp In wdRng.ShapeRange
With wdShp
If Not .TextFrame Is Nothing Then
MsgBox .TextFrame.TextRange.Text
End If
End With
Next
.Collapse wdCollapseEnd
.Find.Execute
Loop
End If
End With
.Close SaveChanges:=wdDoNotSaveChanges
End With
.Quit
End With
Set wdRng = Nothing: Set wdDoc = Nothing: Set wdApp = Nothing
End Sub
The above code includes message boxes to display the heading names and whatever it finds in the heading range's 'non-text' content. I'll leave it to you to turn the textbox output into whatever else you want it to be. Of course, not all inline & floating shapes have text; the loops find those, too, but I have no idea how you intend to 'read' those.

How to find multiple paragraph properties by MS Word macro

I have a macro that find some properties of the word paragraphs. I need to find '4 Lines or more' paragraphs by using the macro.
I've try this code:
If oPar.LineCount = LineCount + 4 Then
See below for entire code:
Sub CheckKeepLinesTogether()
Application.ScreenUpdating = False
Const message As String = "Check Keep Lines Together"
Dim oPar As Paragraph
Dim oRng As Word.Range
Dim LineCount As Long
For Each oPar In ActiveDocument.Paragraphs
Set oRng = oPar.Range
With oRng
With .Find
.ClearFormatting
.Text = "^13"
.Execute
End With
Set oRng = oPar.Range
If oPar.KeepTogether = False Then
If oPar.LineCount = LineCount + 4 Then
.Select
Selection.Comments.Add Range:=Selection.Range
Selection.TypeText Text:=message
Set oRng = Nothing
End If
End If
End With
Next
Application.ScreenUpdating = True
End Sub
Replace the faulty line with the uncommented code :
'If oPar.LineCount = LineCount + 4 Then
If oPar.Range.ComputeStatistics(wdStatisticLines) >= 4 Then
By the way, you don't need to set Set oRng = oPar.Range twice.
Not tested
Sub CheckKeepLinesTogether()
Application.ScreenUpdating = False
Const message As String = "Check Keep Lines Together"
Dim oPar As Paragraph
Dim oRng As Word.Range
Dim LineCount As Long
For Each oPar In ActiveDocument.Paragraphs
Set oRng = oPar.Range
With oRng
With .Find
.ClearFormatting
.Text = "^13"
.Execute
End With
If oPar.KeepTogether = False Then
If oPar.Range.ComputeStatistics(wdStatisticLines) >= 4 Then
Set oRng = oPar.Range
oRng.Comments.Add Range:=oRng
oRng.TypeText Text:=message
Set oRng = Nothing
End If
End If
End With
Next
Application.ScreenUpdating = True
End Sub

Updating all fields in a Word document except those of type wdFieldDocVariable

I have a procedure which updates all fields in a document.
However I would like to skip the wdFieldDocVariable, the item index should be Type.
Public Sub MyApplicationUpdate()
hdWriteInfoLog ("BEGIN MACRO: MyApplicationUpdate")
Dim oTOC As TableOfContents
Dim oField As Field
' Update Fields in all document StoryRanges
Dim oStory As Range
For Each oStory In ActiveDocument.StoryRanges
oStory.Fields.Update
If oStory.StoryType <> wdMainTextStory Then
While Not (oStory.NextStoryRange Is Nothing)
Set oStory = oStory.NextStoryRange
oStory.Fields.Update
Wend
End If
Next oStory
Set oStory = Nothing
' Update all TablesOfContents
For Each oTOC In ActiveDocument.TablesOfContents
oTOC.Update
Next oTOC
hdWriteInfoLog ("END MACRO: MyApplicationUpdate")
End Sub
I think, I have found the answer, I believe there is a more efficient way of doing this, but at least it works...
' Test procedure
Public Sub MyApplicationUpdate()
hdWriteInfoLog ("BEGIN MACRO: MyApplicationUpdate")
Dim oTOC As TableOfContents
Dim oField As Field
Dim oField2 As Field
' Update Fields in all document StoryRanges
Dim oStory As Range
For Each oStory In ActiveDocument.StoryRanges
For Each oField2 In oStory.Fields
If Not oField2.Type = wdFieldDocVariable Then
oField2.Update
End If
Next oField2
If oStory.StoryType <> wdMainTextStory Then
While Not (oStory.NextStoryRange Is Nothing)
Set oStory = oStory.NextStoryRange
' oStory.Fields.Update
For Each oField2 In oStory.Fields
If Not oField2.Type = wdFieldDocVariable Then
oField2.Update
End If
Next oField2
Wend
End If
Next oStory
Set oStory = Nothing
' Update all TablesOfContents
For Each oTOC In ActiveDocument.TablesOfContents
oTOC.Update
Next oTOC
hdWriteInfoLog ("END MACRO: MyApplicationUpdate")
End Sub

Searching for Text in Header Section of A Word Document

I am trying to confirm if a document contains some text, the only problem is this text is in the Header. This is the code I am using which constantly returns false even though the text exists:
Set CurrentDoc = Documents.Open("a.doc")
With CurrentDoc.Sections(1).Headers(wdHeaderFooterFirstPage).Range.Find
.Text = "This is the text to find"
.Forward = True
.Execute
If (.Found = True) Then Debug.Print "Match"
End With
The following also doesn't seem to work (I assume .Content doesn't include header/footers):
With CurrentDoc.Content.Find
.Text = "This is the text to find"
.Forward = True
.Execute
If (.Found = True) Then Debug.Print "Match"
End With
Any help would be greatly appreciated.
You're probably trying to search in the wrong section/headertype. You could try this code:
Dim rng As Range
Dim intSecCount As Integer
Dim intHFType As Integer
intSecCount = ActiveDocument.Sections.Count
For intSection = 1 To intSecCount
With ActiveDocument.Sections(intSection)
For intHFType = 1 To 3
Set rng = ActiveDocument.Sections(intSection).Headers(intHFType).Range
rng.Find.Execute findtext:="This is the text to find", Forward:=True
If rng.Find.Found = True Then
Debug.Print "Match"
End If
Next intHFType
End With
Next intSection
I found the answer on this site and it's a lot more complex than initially thought: http://word.mvps.org/faqs/customization/ReplaceAnywhere.htm
The following code is from the site above, in addition to searching the entire document it includes text replace functionality:
Public Sub FindReplaceAnywhere()
Dim rngStory As Word.Range
Dim pFindTxt As String
Dim pReplaceTxt As String
Dim lngJunk As Long
Dim oShp As Shape
pFindTxt = InputBox("Enter the text that you want to find.", "FIND" )
If pFindTxt = "" Then
MsgBox "Cancelled by User"
Exit Sub
End If
TryAgain:
pReplaceTxt = InputBox( "Enter the replacement." , "REPLACE" )
If pReplaceTxt = "" Then
If MsgBox( "Do you just want to delete the found text?", vbYesNoCancel) = vbNo Then
GoTo TryAgain
ElseIf vbCancel Then
MsgBox "Cancelled by User."
Exit Sub
End If
End If
'Fix the skipped blank Header/Footer problem
lngJunk = ActiveDocument.Sections( 1 ).Headers( 1 ).Range.StoryType
'Iterate through all story types in the current document
For Each rngStory In ActiveDocument.StoryRanges
'Iterate through all linked stories
Do
SearchAndReplaceInStory rngStory, pFindTxt, pReplaceTxt
On Error Resume Next
Select Case rngStory.StoryType
Case WdStoryType.wdEvenPagesHeaderStory, _
WdStoryType.wdPrimaryHeaderStory, _
WdStoryType.wdEvenPagesFooterStory, _
WdStoryType.wdPrimaryFooterStory, _
WdStoryType.wdFirstPageHeaderStory, _
WdStoryType.wdFirstPageFooterStory
If rngStory.ShapeRange.Count > 0 Then
For Each oShp In rngStory.ShapeRange
If oShp.TextFrame.HasText Then
SearchAndReplaceInStory oShp.TextFrame.TextRange, pFindTxt, pReplaceTxt
End If
Next
End If
Case Else
'Do Nothing
End Select
On Error GoTo 0
'Get next linked story (if any)
Set rngStory = rngStory.NextStoryRange
Loop Until rngStory Is Nothing
Next
End Sub
Public Sub SearchAndReplaceInStory(ByVal rngStory As Word.Range, ByVal strSearch As String , ByVal strReplace As String)
With rngStory.Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = strSearch
.Replacement.Text = strReplace
.Wrap = wdFindContinue
.Execute Replace:=wdReplaceAll
End With
End Sub