简体   繁体   中英

VBA in Word: If then to toggle bookmarks hidden/unhidden

This VBA code seems like it should work to toggle hidden = True/ False on bookmarks in Word, but it doesn't.

Private Sub Instructions_Click()

If ActiveDocument.Bookmarks("InstText").Range.Font.Hidden = True Then

Bookmarks("InstText").Range.Font.Hidden = False

Else

Bookmarks("InstText").Range.Font.Hidden = True

End If

End Sub

This next one works (if you click the Instructions button, the appropriate bookmarked text is unhidden)

Private Sub Instructions_Click()

ActiveDocument.Bookmarks("InstText").Range.Font.Hidden = False

End Sub

Another idea I saw is this one:

Private Sub Instructions_Click()

ActiveDocument.Bookmarks("InstText").Range.Font.Hidden = Not  ActiveDocument.Bookmarks("InstText").Range.Font.Hidden

Which is supposed to flip it to whatever it's not, basically. But that doesn't work for me.

Can anyone tell me what's wrong with the first one? I'm guessing that the hidden property can't be used as a condition for some reason, but -- why not? Or is it something else? What's the best way to do this?

Add this code to Normal > NewMacros:

Sub Toggle_Bookmarks()
    ActiveWindow.View.ShowBookmarks = Not ActiveWindow.View.ShowBookmarks
End Sub
  1. Right-click Microsoft Word Ribbon
  2. Customize Quick Access Toolbar
  3. Above left list, choose command from macros
  4. Select Normal.Newmacros.Toggle_Bookmarks
  5. Click Add
  6. Click OK

Now you have a toggle in the quick Access toolbar to click on to toggle bookmarks.

This doesn't answer the question, but it is some insight for people using his question for their own problem.

For some reason, the if statement doesn't compute.Range.Font.Hidden = False. It does, however, compute if you use.Range.Font.Hidden = True.

So you've got to use Else: to work around it. Kind of a double negative situation.

'SF1

If ActiveDocument.Bookmarks("SF1").Range.Font.Hidden = True Then

Else: ActiveDocument.Bookmarks("SF1X").Range.Font.Hidden = False

End If``

In my own Word add-in, I display a list of all the bookmarks found. The user clicks on the bookmark (or multiple bookmarks) and click the Toggle button to switch the visibility.

My routine loops through all the selected bookmarks and uses these two lines of code:

.Bookmarks(intHideShowBookmark).Select
.Bookmarks(intHideShowBookmark).Range.Font.Hidden = Not _ .Bookmarks(intHideShowBookmark).Range.Font.Hidden

Which is using the third option you mentioned. Hope that helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM