View Single Post
 
Old 03-25-2024, 02:39 AM
gmaxey gmaxey is offline Windows 10 Office 2019
Expert
 
Join Date: May 2010
Location: Brasstown, NC
Posts: 1,601
gmaxey is just really nicegmaxey is just really nicegmaxey is just really nicegmaxey is just really nicegmaxey is just really nice
Default

Andrew,



Clearly Method C. Thank you. I had forgotten all about the ^d switch for finding fields.
I've taken this a bit further to permit jumping forward or back to the next field of type. A bit more code but wanted some escapes and options for looping.

Code:
Sub FieldJumper()
  JumpToTypeField "REF", False
End Sub
Sub JumpToTypeField(strType As String, Optional bNext As Boolean = True)
'Method C
Dim oRng As Range, oRngRef As Range
Dim bShowCodes As Boolean
Dim lngFind As Long, lngCount As Long
Dim strMsg As String
  lngCount = 0
  lngFind = 0
  Set oRng = ActiveDocument.Range
  bShowCodes = ActiveWindow.View.ShowFieldCodes
  ActiveWindow.View.ShowFieldCodes = True
  With oRng.Find
    .ClearFormatting
    .Text = "^d " & strType
    .Forward = bNext
    .Wrap = wdFindStop
    .MatchCase = False
    Do While .Execute
      lngCount = lngCount + 1
      If lngCount > 1 Then Exit Do
    Loop
  End With
Wrap:
  Set oRng = Selection.Range.Duplicate
  Select Case lngCount
    Case 0
      MsgBox "There are no " & strType & " fields in this document.", vbInformation + vbOKOnly, "NOT FOUND"
    Case Else
      With oRng.Find
        .ClearFormatting
        .Text = "^d " & strType
        .Forward = bNext
        .Wrap = lngFind
        .MatchCase = False
        If .Execute Then
          oRng.Select
        Else
          If lngCount > 1 Or Selection.Fields.Count = 0 Then
            ActiveWindow.View.ShowFieldCodes = False
            strMsg = "There are no subsequent " & strType & " fields in the document. Do you want to loop to the beginning of the document?"
            If Not bNext Then strMsg = "There are no preceding " & strType & " fields in the document. Do you want to loop to the end of the document?"
            If MsgBox(strMsg, vbQuestion + vbYesNo, "LOOP") = vbYes Then
              lngFind = 1
              ActiveWindow.View.ShowFieldCodes = True
              GoTo Wrap
            End If
          Else
            ActiveWindow.View.ShowFieldCodes = False
            MsgBox "There are no preceding or subsequent " & strType & " fields in this document.", vbInformation + vbOKOnly, "SINGULAR FIELD"
          End If
        End If
      End With
    End Select
lbl_Exit:
  ActiveWindow.View.ShowFieldCodes = bShowCodes
  Exit Sub
End Sub
__________________
Greg Maxey
Please visit my web site at http://www.gregmaxey.com/
Reply With Quote