Creating automatic fill in word document with drop-down list content control
firt of all I need to admit, that I know absolutely nothing about creating macros in Word, but I would like to make it a little easier for myself to work on documents at my workplace, and to that end I would like to create a macro that will change the text in a Word document depending on the option selected in the drop-down list content control.
For example, in the drop-down list inserted into a Word document I have:
- option 1
- option 2
If I select option 1 from the list, I want the text assigned to option 1 to appear in a specific place in the Word document. If I change the selection from option 1 to option 2, I want the text assigned to option 1 to be replaced by the text assigned to option 2. If neither option is selected, I want no text to be displayed at that particular location in the document.
Is it at all possible to create code for a macro that would work in this way? If so, I would appreciate your help.
I tried to describe this in GPT chat, but what I was getting did not work exactly as I described above. The effect of working with GPT chat was that the text would only appear if one of the options was already selected when I ran the macro in Word. What's more, the macro created by GPT chat did not respond by changing the text when I selected an option other than the one that was selected when the macro was run.
This is the code I got from ChatGPT:
Sub Makro6()
Dim cc As Contentcontrol
Dim selectedValue As String
For Each cc In ActiveDocument.ContentControls
If cc.Title = "Subsystem" Then
selectedValue = cc.Range.Text
Exit For
End If
Next cc
Select Case selectedValue
Case "Option1"
UpdateOrCreateBookmark "Option_1", "Text for Option1"
ToggleBookmarkVisibility "Option_1", True
ToggleBookmarkVisibility "Option_2", False
Case "Option2"
UpdateOrCreateBookmark "Option_1", "Text for Option2"
ToggleBookmarkVisibility "Option_1", False
ToggleBookmarkVisibility "Option_2", True
Case Else
ToggleBookmarkVisibility "Option_1", False
ToggleBookmarkVisibility "Option_2", False
End Select
End Sub
Sub UpdateOrCreateBookmark(bookmarkName As String, bookmarkText As String)
Dim bm As Bookmark
On Error Resume Next
Set bm = ActiveDocument.Bookmarks(bookmarkName)
On Error GoTo 0
If bm Is Nothing Then
' Bookmark does not exist add new one
ActiveDocument.Bookmarks.Add bookmarkName, Selection.Range
ActiveDocument.Bookmarks(bookmarkName).Range.Text = bookmarkText
Else
' Bookmark exists update its text
bm.Range.Text = bookmarkText
End If
End Sub
Sub ToggleBookmarkVisibility(bookmarkName As String, visible As Boolean)
Dim bm As Bookmark
On Error Resume Next
Set bm = ActiveDocument.Bookmarks(bookmarkName)
On Error GoTo 0
If bm Is Nothing Then
' Bookmark does not exist
Exit Sub
Else
' Show/hide bookmark
bm.Range.Font.Hidden = Not visible
End If
End Sub
Comments
Post a Comment