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

时间:2015-03-31 14:47:40

标签: vba excel-vba combobox event-handling

我有一张包含40个组合框的Excel表格。 我有一个必须执行的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: 谢谢David Zemens。您的回答帮助我调整它并使其适用于我的具体问题。这是我现在的代码,工作正常! (我使用了这个主题: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

谢谢!

1 个答案:

答案 0 :(得分:1)

如果所有组合框必须具有允许_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会在执行其余代码之前中止该过程。