Link to home
Start Free TrialLog in
Avatar of wasabi3689
wasabi3689Flag for United States of America

asked on

How to debug this code

Sub Remove_RefFrombody()

Dim doc As Document
  Dim fld As Field
  Set doc = ActiveDocument
  For Each fld In doc.Fields
    fld.Select
    If fld.Type = wdFieldRef Then
      fld.Unlink
    End If
  Next
  Set fld = Nothing
  Set doc = Nothing
  
End Sub

Open in new window


When I run this code, it throws out an error like the attached image, how do I fix it?

From the error image, if I click on "End", the program can continue to run. How to express press "End" from method?

For example,

 If fld.Type = wdFieldRef Then
      fld.Unlink
Else
    End

    End If
Avatar of Martin Liss
Martin Liss
Flag of United States of America image

You forgot to attach the image.

Are you actually using Visual Basic Classic which is VB6?
How to express press "End" from method?
if you want to exit in a For Loop, you can try:

Exit For
https://www.tutorialspoint.com/vba/vba_exit_for_statement.htm
Or you can leave the procedure with
Exit Sub

Incidentally, setting the used objects to Nothing does nothing that doesn't happen automatically when leaving the procedure, so it wouldn't matter if these lines were missed. Also there is no need to select the field first.
Sub Remove_RefFrombody()
    Dim doc As Document
    Dim fld As Field
    
    Set doc = ActiveDocument
    For Each fld In doc.Fields
        If fld.Type = wdFieldRef Then
            fld.Unlink
        Else
            Exit Sub
        End If
    Next fld
End Sub

Open in new window

However, with that you would leave the loop at the first field that isn't a Ref field, omitting any later Ref fields, so, unless that is what you really want, simply carry on:

Sub Remove_RefFrombody()
    Dim doc As Document
    Dim fld As Field
    
    Set doc = ActiveDocument
    For Each fld In doc.Fields
        fld.Select
        If fld.Type = wdFieldRef Then
            fld.Unlink
        End If
    Next fld
End Sub

Open in new window

Oops. I left the Select in the second snippet, so it should be:
Sub Remove_RefFrombody()
    Dim doc As Document
    Dim fld As Field
    
    Set doc = ActiveDocument
    For Each fld In doc.Fields
        If fld.Type = wdFieldRef Then
            fld.Unlink
        End If
    Next fld
End Sub

Open in new window

Avatar of wasabi3689

ASKER

Here is my attachment
Capture100.JPG
Capture101.JPG
ASKER CERTIFIED SOLUTION
Avatar of Karen
Karen
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial