首页 > 解决方案 > 如何根据excel中的用户选择禁用复选框

问题描述

我需要根据变量列表禁用复选框。例如,如果用户在列表框中选择“西班牙”,则仅应允许某些复选框货币。

  1. 我有一个基于用户选择的值为 1 或 0 的货币表,并且得到更新。零表示货币不可用。
  2. 我有一个宏,它读取列表并将禁用或启用各个列表框。但是,这甚至是 Worksheet_Change ”,并且不会通过列表框选择更改来调用它。尽管我的范围在用户进行选择后会更新。所以我认为我需要一个基于模块的宏,当用户进行列表框选择时将调用该宏,但很难修改我当前的宏。

我目前的代码是:

Private Sub Worksheet_Change(ByVal Target As Range)

Dim R As Range, c As Range, cb As OLEObject

' set a range where the cell will be either 1 or 0 depending on country selection

Set R = Me.Range("C115:C135")
If Not Intersect(Target, R) Is Nothing Then

' sets the checbox to zero if related cell value in range is zero

    For Each c In Intersect(Target, R)
        For Each cb In Me.OLEObjects
        ' Identifies the relevant Checkbox name based on related cell address
            If cb.Name Like "CheckBox" & Val(Split(c.Address, "$")(2)) - 14 Then
                cb.Enabled = c.Value > 0
            End If
        Next cb
    Next c
End If
End Sub

标签: excelvba

解决方案


你需要在这里有点棘手。

首先,在您拥有已发布代码的所需工作表中,编写一个像这样的新子:

Sub MyMacro()
Call Worksheet_Change(ActiveCell) 'change ActiveCell for the range you want to be the target
End Sub

然后,从ChangeListbox 的事件中,尝试:

Private Sub ComboBox1_Change()
Call Hoja1.MyMacro 'Replace Hoja1 with the name of your worksheet in VBA.
End Sub

推荐阅读