如何从一系列组合框中读取值?

how to read the value from a range of comboboxes?

我有一个 Excel sheet,其中包含 40 个组合框。 我有一个必须执行的 worksheet_change 事件,只有当这 40 个组合框具有指定值时。

我有这段代码(我在这里找到:Get the selected value of a activex combobox using vba)来读取组合框的值。 我想我可以循环读取每个组合框。

但我的问题是设置使用事件处理程序值的规则。 无论条件是否匹配,我都可以创建 1 或 0 的东西(变量)吗?

我有这段代码可以读取组合框的值:

Private Sub Worksheet_Change(ByVal Target As Range)

Dim ws As Worksheet
Dim cboCorpConsumer As ComboBox
Dim a As String
Dim i As Integer

Set ws = Worksheets("simulator VER")
Set cboCorpConsumer = ws.OLEObjects("ComboBox2).Object

我怎样才能达到上述目标?或者我应该为每个组合框使用一个规则?

if combobox2.value = 1 then
if combobox3.value = 1 then
etc. etc.

if combobox40.value = 1 then execute event handler

编辑 2: 谢谢大卫泽门斯。您的回答帮助我对其进行了调整并使其适用于我的特定问题。这是我现在拥有的代码,可以正常工作! (我使用了这个主题:Call a function when only a specific Excel cell changes on Formula Recalculation 来确保代码仅在更改 2 个特定单元格时才 运行)。

Private Sub Worksheet_Change(ByVal Target As Range)

Dim objOLE As OLEObject
Dim cb As ComboBox
Dim a As String
Dim i As Integer
Application.ScreenUpdating = False

If Target.Address = Sheets("simulator VER").Range("E6").Address Then

'## Make sure ALL comboboxes have the value of "1" before proceeding
For Each objOLE In Me.OLEObjects
    If TypeName(objOLE.Object) = "ComboBox" Then
        Set cb = objOLE.Object
        If cb.Value <> "No Promotion" Then GoTo Earlyexit
    End If
Next

'### The rest of your procedure code goes here:
With Worksheets("Simulator VER")
.Range("O21:O60").Copy
.Range("P21:P60").PasteSpecial Paste:=xlPasteValues
End With

Else
    If Target.Address = Sheets("simulator VER").Range("E7").Address Then
        '## Make sure ALL comboboxes have the value of "1" before proceeding
        For Each objOLE In Me.OLEObjects
        If TypeName(objOLE.Object) = "ComboBox" Then
            Set cb = objOLE.Object
            If cb.Value <> "No Promotion" Then GoTo Earlyexit
        End If
        Next

        '### The rest of your procedure code goes here:
        With Worksheets("Simulator VER")
        .Range("O21:O60").Copy
        .Range("P21:P60").PasteSpecial Paste:=xlPasteValues
        End With
    Else
    End If
End If

Earlyexit:

Application.ScreenUpdating = True

End Sub

谢谢!

如果 all 组合框必须具有指定值才能触发 _Change 事件,您可以这样做:

Private Sub Worksheet_Change(ByVal Target As Range)

Dim objOLE as OLEObject
Dim cb As ComboBox
Dim a As String
Dim i As Integer

'## Make sure ALL comboboxes have the value of "1" before proceeding
For each objOLE in Me.OLEObjects
    If TypeName(objOLE.Object = "ComboBox") Then
        Set cb = objOLE.Object
        If cb.Value <> 1 Then GoTo EarlyExit
    End If
Next

'### The rest of your procedure code goes here:

EarlyExit:

End Sub

注意: 从技术上讲,_Change 事件每次都会触发,但 GoTo EarlyExit 会在执行其余代码之前中止该过程。