Search code examples
exceltextboxradio-buttonvba

VBA Excel : Populate TextBox with specific string of text when Option Button is selected


I developed a Form in Excel (2016) and I am trying (with VBA) to configure its behavior so that if the user selects a particular option button, two additional things happen:

  1. A checkbox further down on the form is automatically checked.
  2. A text box further down on the form automatically displays a set string of text.

More specifically, if the user selects OptionButtonABC, then ...

  1. CheckBoxNone should become checked
  2. TextBoxCompanyName (which does not display any text by default) should now display the string: 'ABC'.

I initially created a subroutine that just targeted condition 1, and everything worked fine. However, when I try to integrate the code required to handle condition 2, things start to unravel.

Below, you will see the code in its most current state. I have a Private Sub that initiates upon the Click event and then immediately defines a variable as a string. I then set up an if/then statement that specifies what should happen IF OptionButtonABC is true. Namely, CheckBoxNone should be selected (this works fine) AND TextBoxCompanyName should now display the string 'ABC'.

Private Sub OptionButtonABC_Click()
Dim Variable_ABC As String
Variable_ABC = ABC
If Me.OptionButtonABC.Value = True Then
Me.CheckBoxNone = True And Me.TextBoxCompanyName.Text = Variable_ABC
End If
End Sub

The desired behavior should (theoretically) be pretty easy to achieve, but my experience with VBA is still pretty limited, so I am reaching out to the community for a bit of advice. As I mentioned above, the code above works for the first condition. However, I am still unable to get the string of text ('ABC') to show up in the text box.

Thanks in advance for any advice you may offer.


Solution

  • Private Sub OptionButtonABC_Click()
    Dim Variable_ABC As String
    Variable_ABC = "ABC" 'String Values uses double quotes
    If Me.OptionButtonABC.Value = True Then
      Me.CheckBoxNone = True
      Me.TextBoxCompanyName.Text = Variable_ABC
    End If
    End Sub
    

    The operator AND must be used only in the IF statement comparison, not in what you want to do.