PDA

View Full Version : [SOLVED:] How Do I Set A Default Variable For An OptionButton?



HTSCF Fareha
08-07-2020, 12:35 AM
I have a simple two option button section in my form. If the user selects Optionbutton1, then TextBox2 is hidden. When they select Optionbutton2, then TextBox2 becomes visible and the user can enter text.


The text entered in TextBox2 should be assigned to variable called "other".


What I am trying to achieve is if Optionbutton1 is selected, a default value for the variable "other" will be 'none'. Obviously if the user selects Optionbutton2, then variable "other" should be whatever is input by the user in TextBox2.


The text entered for the variable "other" will be input at the Bookmark "other".
I'm new to VBA and have searched Google for the answer, but have not had any luck. Hope this makes sense?


I have tried to declare the variable "other" as "none", but it doesn't hold this value if Optionbutton1 is selected. I've added the two lines that show what I thought would work.



Dim Other As None
Other = "None"



Private Sub OptionButton1_Click()
For Each objCtrl In Me.Controls
If OptionButton1.Value Then TextBox2.Visible = False
Next
OptionButton1.Visible = True
OptionButton2.Visible = True

End Sub

Private Sub OptionButton2_Click()
For Each objCtrl In Me.Controls
If OptionButton2.Value Then TextBox2.Visible = True
Next
End Sub
'
'
'
Dim Other As Range
Set Other = ActiveDocument.Bookmarks("Other").Range
Other.Text = Me.TextBox2.Value



Hope this makes sense?

Thanks!

gmayor
08-07-2020, 01:25 AM
You need something like


Option Explicit

Private Sub UserForm_initialize()
OptionButton1.value = True
End Sub

Private Sub OptionButton1_Change()
If OptionButton1.value = True Then
TextBox2.Visible = False
TextBox2.Text = "None"
Else
TextBox2.Visible = True
TextBox2.Text = ""
End If
End Sub

Private Sub CommandButton1_Click()
Dim oRng As Range
If ActiveDocument.Bookmarks.Exists("Other") = True Then
Set oRng = ActiveDocument.Bookmarks("Other").Range
oRng.Text = TextBox2.Text
oRng.Bookmarks.Add "Other"
End If
Unload Me
End Sub

HTSCF Fareha
08-07-2020, 02:07 AM
You need something like


Option Explicit

Private Sub UserForm_initialize()
OptionButton1.value = True
End Sub

Private Sub OptionButton1_Change()
If OptionButton1.value = True Then
TextBox2.Visible = False
TextBox2.Text = "None"
Else
TextBox2.Visible = True
TextBox2.Text = ""
End If
End Sub

Private Sub CommandButton1_Click()
Dim oRng As Range
If ActiveDocument.Bookmarks.Exists("Other") = True Then
Set oRng = ActiveDocument.Bookmarks("Other").Range
oRng.Text = TextBox2.Text
oRng.Bookmarks.Add "Other"
End If
Unload Me
End Sub

This works great, thanks!

I just had to remove

Private Sub UserForm_initialize()