繁体   English   中英

根据单选按钮选择组合(VBA Excel)用可变文本填充文本框

[英]Fill a textbox with varaible text depending on Radio Button selection combo (VBA Excel)

我需要一些帮助来获取正确的代码来执行以下操作:

  • 我在用户表单的框架内有 4 组单选按钮
  • 每个组都是一个简单的是/否单选按钮
  • 我有一个文本框,我想根据所选的“是”单选按钮的数量自动填充 AD 的分数范围。
  • “否”复选框真的不应该对文本框做任何事情

    • 用户表单名称 = TP_UF
    • 框架名称 = fun_opt_frame
    • “是”的选项按钮名称 = fun_score_yes1-4
    • 文本框名称 = fun_scorebox

逻辑:

  • 4 是 = A
  • 3 是 = B
  • 2 是 = C
  • 1 是 = D

选择 yesses 的顺序无关紧要,它是一个总数。 我尝试使用框架使用代码,但不确定这是否是最好的方法。 不需要这些单选按钮的框架,除了可能使编码更容易之外的任何原因。 所以如果没有必要让这个工作,我可以扔掉框架。

我不知道从哪里开始。 任何帮助,将不胜感激。

图片

您理解的最快和最简单的方法是 - 我猜 - 以下代码。 您必须将代码放入用户窗体的类模块中。

Option Explicit

Dim opt1 As Byte
Dim opt2 As Byte
Dim opt3 As Byte
Dim opt4 As Byte

Private Sub opt1Yes_Click()
    opt1 = 1
    EvalOpt
End Sub
Private Sub opt1No_Click()
    opt1 = 0
    EvalOpt
End Sub
Private Sub opt2yes_Click()
    opt2 = 1
    EvalOpt
End Sub
Private Sub opt2No_Click()
    opt2 = 0
    EvalOpt
End Sub
Private Sub opt3yes_Click()
    opt3 = 1
    EvalOpt
End Sub
Private Sub opt3No_Click()
    opt3 = 0
    EvalOpt
End Sub
Private Sub opt4yes_Click()
    opt4 = 1
    EvalOpt
End Sub
Private Sub opt4No_Click()
    opt4 = 0
    EvalOpt
End Sub

Private Sub EvalOpt()
Dim sumOpt As Byte
Dim res As String
    sumOpt = opt1 + opt2 + opt3 + opt4
    Select Case sumOpt
    Case 1: res = "D"
    Case 2: res = "C"
    Case 3: res = "B"
    Case 4: res = "A"
    Case Else: res = ""
    End Select
    Me.fun_scorebox.text = res
End Sub

我假设选项按钮被命名为 opt1Yes、opt1No、opt2Yes、opt2No 等。更高级的解决方案可能是使用 classe 模块并以这种方式“收集”选项按钮。

我最终以不同的方式解决这个问题,并使用计数器使其工作。 谢谢您的帮助! 在这里发布代码以防其他人需要它。

    Option Explicit

    Private Sub OptionButton1_Change()
    set_counter
    End Sub

    Private Sub OptionButton2_Change()
    set_counter
    End Sub

    Private Sub OptionButton3_Change()
    set_counter
    End Sub

    Private Sub OptionButton4_Change()
    set_counter
    End Sub

    Private Sub OptionButton5_Change()
    set_counter
    End Sub

   Private Sub OptionButton6_Change()
   set_counter
   End Sub

   Private Sub OptionButton7_Change()
   set_counter
   End Sub

   Private Sub OptionButton8_Change()
   set_counter
   End Sub

   Private Sub set_counter()
    Dim x As Integer, counter As Integer
     Me.TextBox1.Value = ""
     counter = 0
     For x = 1 To 8 Step 2
       If Me.Controls("OptionButton" & x).Value = True Then counter = counter + 1
     Next x
        Me.TextBox1.Value = Choose(counter, "D", "C", "B", "A")
   End Sub

  Private Sub UserForm_Activate()
    Me.TextBox1.Value = ""
  End Sub

  Private Sub UserForm_Click()
    Dim x As Integer
      Me.TextBox1.Value = ""
      For x = 1 To 8
         Me.Controls("OptionButton" & x).Value = False
      Next x
  End Sub

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM