I'm attempting to create a Word document where a user can select a State in the dropdown and be presented with a link specific to that state.
To achieve this, I have a DropDown List Content Control
with two options: Texas, and Oklahoma.
I have two blocks of text. One is bookmarked TexasText, the other is bookmarked Oklahoma text. The goal is for the user to select a state from the dropdown, and only see the specified text-block.
I'm using the following code in ThisDocument as an event handler:
Private Sub Document_ContentControlOnEnter(ByVal ContentControl As ContentControl)
If ContentControl.Title = "StateDropdown" Then
Dim selectedValue As String
Dim texasText As Range, oklahomaText As Range
' Get the selected value from the dropdown form field
selectedValue = ContentControl.DropdownListEntries(ContentControl.DropdownListEntries(1).Index).Text
' Get the bookmark ranges
Set texasText = ActiveDocument.Bookmarks("TexasText").Range
Set oklahomaText = ActiveDocument.Bookmarks("OklahomaText").Range
' Check if "Show All" is selected
If selectedValue = "Show All" Then
' Show both Texas and Oklahoma text
texasText.Font.Hidden = False
oklahomaText.Font.Hidden = False
ElseIf selectedValue = "Texas" Then
' Show Texas and hide Oklahoma text
texasText.Font.Hidden = False
oklahomaText.Font.Hidden = True
ElseIf selectedValue = "Oklahoma" Then
' Show Oklahoma and hide Texas text
texasText.Font.Hidden = True
oklahomaText.Font.Hidden = False
End If
End If
End Sub
And this is in the Module:
Sub UpdateTextVisibility()
Dim selectedValue As String
Dim texasText As Range, oklahomaText As Range
' Get the selected value from the dropdown form field
selectedValue = ActiveDocument.SelectContentControlsByTitle("StateDropdown")(1).DropdownListEntries(ActiveDocument.SelectContentControlsByTitle("StateDropdown")(1).DropdownListEntries(1).Index).Text
' Get the bookmark ranges
Set texasText = ActiveDocument.Bookmarks("TexasText").Range
Set oklahomaText = ActiveDocument.Bookmarks("OklahomaText").Range
' Hide or show text based on the selected value
If selectedValue = "Texas" Then
texasText.Font.Hidden = False
oklahomaText.Font.Hidden = True
ElseIf selectedValue = "Oklahoma" Then
texasText.Font.Hidden = True
oklahomaText.Font.Hidden = False
ElseIf selectedValue = "Show All" Then
texasText.Font.Hidden = False
oklahomaText.Font.Hidden = False
End If
End Sub
My expectation is that when I update the dropdown selection, the content hides / shows accordingly. This is not occurring.
You are using the OnEnter event, which only fires when you enter the content control, not when you change the values.
If you use the OnExit event, the macro would run when you tab out of the content control. Unfortunately, Microsoft has never written an OnChange event, which is probably how you expect the dropdown to work.
Here is Greg Maxey's page about this shortcoming: Content Controls And here is his page with programming to create a custom OnChange event: Content Control Custom Events