VBA - 选择单选按钮时触发宏

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22867387/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 02:40:15  来源:igfitidea点击:

VBA - trigger macro when radio button is selected

excelvbaexcel-vba

提问by teepee

I am having trouble running a macro automatically when I select a radio button option. There are two radio-button options, which are linked to the cell named "SimType" on the sheet codenamed "MAIN". I have adapted the following code from MSDN and have included it in the module for the MAIN worksheet but cannot get it to function:

当我选择单选按钮选项时,我无法自动运行宏。有两个单选按钮选项,它们链接到代号为“MAIN”的工作表上名为“SimType”的单元格。我已经改编了 MSDN 中的以下代码,并将其包含在 MAIN 工作表的模块中,但无法使其正常工作:

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim KeyCells As Range
    Set KeyCells = Range("SimType")
    If Not Application.Intersect(KeyCells, Range(Target.Address)) Is Nothing Then
       RefreshSimsList 
    End If
End Sub

I understand Target refers to the ActiveCell so when I manually enter values of 1 or 2 into Range("SimType"), the macro triggers. However, when the cell is altered by the linked radio-buttons, no action is triggered. What can I do to have the sheet recognize that the value has been changed without it being the ActiveCell?

我了解 Target 指的是 ActiveCell,因此当我手动将 1 或 2 的值输入 Range("SimType") 时,宏会触发。但是,当单元格被链接的单选按钮更改时,不会触发任何操作。我该怎么做才能让工作表识别出该值已更改而不是 ActiveCell?

采纳答案by Siddharth Rout

Place this code in a module

将此代码放在一个模块中

Sub OptCommon()
    '
    '~~> Rest of the code
    '
End Sub

And simply right click on both the option button and assign macro to it. Now not only the cell value will change but the macro will also run.

只需右键单击选项按钮并为其分配宏。现在不仅单元格值会改变,宏也会运行。