检测是否在 VBA 中选择了表单控件选项按钮表单、控件、按钮、选项

2023-09-06 22:07:05 作者:℡爱情不过扯犊子°

我有一个使用 ActiveX 选项按钮工作得很好的代码.但是,我希望宏也能在 Mac 上运行,所以我试图用表单控件替换我的 ActiveX 控件.使用 ActiveX,为了检查是否选择了我的两个选项按钮之一,我所要做的就是:

I have a code that work just fine using ActiveX option buttons. However, I want the macro to run on a Mac as well so I am trying to replace my ActiveX controls with form controls. With ActiveX, all I had to do in order to check if one of my two option buttons was selected is:

    Sub OptionButton1_Click
    If OptionButton1.Value = true then
        (action...)
    End if
    End sub

我一直在尝试在 Google 上找到表单控件的等效项,但每次我得到一个:

I have been trying to find an equivalent for Form Controls on Google but each time I get an:

对象需要错误

非常感谢@L42 和@Sai Nishank 的回答!现在,如果我想签入 OptionButton_Click 如果来自其他组的选项按钮为 true 怎么办?我尝试了这种语法,但收到一条错误消息:找不到编译错误方法或数据"

Thank you very much for your answers @L42 and @Sai Nishank! Now what if I want to check in an OptionButton_Click if an option button from an other group is true ? I tried this syntax but I get an error message : "Compile error Method or Data not found"

    Sub USDButton_Click()
    MsgBox "USD"
    If Sheet1.BTUButton = True Then
    (action1)
    End If
     If Sheet1.kWhButton = True Then
    (action2)
     End If

我不确定 BTUButton 是否是按钮的正确名称,但我不知道在哪里检查,表单控件没有 ActiveX 那样方便的右键单击 > 属性"

I am not sure if BTUButton is the correct name of the button, but I don't where to check, form controls don't have that handy "Right Click > Properties" like ActiveX

推荐答案

您应该从所有选项按钮中删除 .Value,因为选项按钮不保存结果值,选项组控件可以.如果您省略 .Value,则默认界面将按照您的预期报告选项按钮状态.您应该在 commandbutton_click 事件下编写所有相关代码,因为每当单击 commandbutton 时,选项按钮操作都会运行.

You should remove .Value from all option buttons because option buttons don't hold the resultant value, the option group control does. If you omit .Value then the default interface will report the option button status, as you are expecting. You should write all relevant code under commandbutton_click events because whenever the commandbutton is clicked the option button action will run.

如果您想在单击选项按钮时运行操作代码,请不要为此编写 if 循环.

If you want to run action code when the optionbutton is clicked then don't write an if loop for that.

示例:

Sub CommandButton1_Click
    If OptionButton1 = true then
        (action code...)
    End if
End sub

Sub OptionButton1_Click   
    (action code...)
End sub