VBA 根据选项按钮选择更新文本框值

VBA Update Textbox Value based on Option Button Selection

我正在处理一个 vba excel 用户表单,我被困在一个名为 "Textbox6" 的文本框不会在某些条件到位时更新的地方 - 比如选择或不选择选项按钮。

也就是说。如果 Optionbuttton10 为真 "only",则 Textbox6 显示单元格 D3 中的值

如果 "OptionButton10" 为真且 "Optionbutton2" 为真,那么我希望 Textbox6 显示单元格 E3

这是我目前的代码,"looks" 它应该可以工作,但我遗漏了一些东西。

Private Sub OptionButton10_Click()
Dim D3 As Variant
Dim E3 As Variant
D3 = Sheets("Systems").Range("D3").Value
E3 = Sheets("Systems").Range("E3").Value

If OptionButton10 = True And ComboBox2 = "Standard" Or ComboBox2 = "Scale-In" Then
TextBox6.Value = D3 'this works'
ElseIf OptionButton10 = True And OptionButton2 = True Then
TextBox6.Value = E3 'this doesn't work'
End If
 TextBox6.Text = Format(TextBox6.Value, "Percent")
End Sub

很难确定,但根据您的意见,您可能想试试这个:

Private Sub OptionButton10_Click()
  Dim D3 As Variant
  Dim E3 As Variant
  D3 = Sheets("Systems").Range("D3").Value
  E3 = Sheets("Systems").Range("E3").Value

  If (OptionButton10 And Not (OptionButton2)) And (ComboBox2 = "Standard" Or ComboBox2 = "Scale-In") Then
    TextBox6.Value = D3                          'this works'
  ElseIf OptionButton10 = True And OptionButton2 = True Then
    TextBox6.Value = E3                          'this doesn't work'
  End If
  TextBox6.text = Format(TextBox6.Value, "Percent")
End Sub

或者,或者这样:

Private Sub OptionButton10_Click()
  Dim D3 As Variant
  Dim E3 As Variant
  D3 = Sheets("Systems").Range("D3").Value
  E3 = Sheets("Systems").Range("E3").Value

  If OptionButton10 And OptionButton2 Then
    TextBox6.Value = E3                          'this doesn't work'
  ElseIf OptionButton10 = True And (ComboBox2 = "Standard" Or ComboBox2 = "Scale-In") Then
    TextBox6.Value = D3                          'this works'
  End If
  TextBox6.text = Format(TextBox6.Value, "Percent")
End Sub

此外,我强烈建议您给按钮和框(包括文本框)起更好的名字。将来当您可以查看您的代码并阅读时,您将非常感激:

If (ProcessFoo and Not(ProcessBar)) and (Baz = "Standard" or Baz = "Scale-In")

*为您的选项和组合框取适当的名称,如果您将它们命名为FooBarBaz,将来您可能会更加困惑比起使用默认名称...

这比您必须返回表单查看 OptionButton10OptionButton2 的文本标签是什么要快得多...

下面是对我有用的解决方案。

我使用了嵌套的 If 语句并添加了 "optionbutton2 = false"

Private Sub OptionButton10_Click()
Dim D3 As Variant
Dim E3 As Variant
D3 = Sheets("Systems").Range("D3").Value
E3 = Sheets("Systems").Range("E3").Value

If ComboBox2 = "Standard" Or ComboBox2 = "Scale-In" Then
  If OptionButton10 = True And OptionButton2 = False Then
     TextBox6.Value = D3 
  ElseIf OptionButton10 = True And OptionButton2 = True Then
     TextBox6.Value = E3 
 End If
End If
TextBox6.Text = Format(TextBox6.Value, "Percent")
End Sub