wasabi3689
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
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
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.
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
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
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
ASKER
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Are you actually using Visual Basic Classic which is VB6?