I have a list of fields (citations from ZOTERO) in one section of MS WORD document and some text with citations in next section. I'd like to match all citations with the text from each field and replace the citation with the field. It can be done easily by hand:
- Go to next field.
- Select and copy field.
- Paste the field in find window.
- ^c as a replace, so the field will be copied instead of the text.
Somehow it's not working in VBA, MS WORD is not responding at all.
Sub CopyAndReplaceNextFieldText()
Dim mySection As Section
Dim myRange As Range
Dim myField As Field
Dim count As Integer
count = 0
' Set the range to the first section in the active document
Set mySection = ActiveDocument.Sections(1)
Set myRange = mySection.Range
' Loop through each field in the range
For Each myField In myRange.Fields
' Increment the count if the field is not a hyperlink
If myField.Type <> wdFieldHyperlink Then
count = count + 1
End If
Next myField
For Each myField In myRange.Fields
myField.Copy
Dim fieldText As String
fieldText = Replace(myField.Result.Text, Chr(13), "")
If IsSubstring(fieldText, ", ") Then
fieldText = Replace(fieldText, ", ", ":")
End If
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
With Selection.Find
.Text = fieldText
.Replacement.Text = "^c"
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Selection.Find.Execute Replace:=wdReplaceAll
Next myField
End Sub