如何为控制TextToShow书签的Yes/No按钮添加第二个书签控制?
Modify VBA Code to Control Two Bookmarks with One Checkbox
Hey there! To add control for a second bookmark using your existing Yes/No checkbox, you just need to extend the ShowHideBookmark subroutine to handle both bookmarks. Here's how you can adjust your code:
Modified VBA Code
Private Sub CheckBoxNo_Change() Call ShowHideBookmark End Sub Sub ShowHideBookmark() ' Declare range variables for both bookmarks Dim Sterilisation As Range Dim SecondBookmark As Range ' Set ranges to your existing and new bookmarks (replace "SecondTextToShow" with your actual bookmark name) Set Sterilisation = ActiveDocument.Bookmarks("TextToShow").Range Set SecondBookmark = ActiveDocument.Bookmarks("SecondTextToShow").Range ' Toggle visibility based on checkbox state If CheckBoxNo.Value = True Then ' Hide both bookmarks With Sterilisation.Font .Hidden = True End With With SecondBookmark.Font .Hidden = True End With ' Update document view to hide hidden text With ActiveWindow.View .ShowHiddenText = False .ShowAll = False End With Else ' Show both bookmarks With Sterilisation.Font .Hidden = False End With With SecondBookmark.Font .Hidden = False End With ' Update document view to show hidden text With ActiveWindow.View .ShowHiddenText = True .ShowAll = True End With End If End Sub
Key Changes Explained:
- Added a second
Rangevariable (SecondBookmark) for your new bookmark. Don’t forget to replace"SecondTextToShow"with the actual name of your second bookmark. - Applied the same font hiding/showing logic to both ranges, so they toggle together with the checkbox.
- Kept the view settings as a single block since they affect the entire document window, not individual bookmarks—no need to repeat them for each bookmark.
Optional Error-Handling Improvement:
If you want to avoid crashes if a bookmark is accidentally deleted, add existence checks before setting the ranges:
' Check if bookmarks exist before accessing them If ActiveDocument.Bookmarks.Exists("TextToShow") Then Set Sterilisation = ActiveDocument.Bookmarks("TextToShow").Range End If If ActiveDocument.Bookmarks.Exists("SecondTextToShow") Then Set SecondBookmark = ActiveDocument.Bookmarks("SecondTextToShow").Range End If
内容的提问来源于stack exchange,提问作者Alex Mcquaid
相关产品推荐
相关产品推荐

