Excel VBA Userform - 在动态comboBox上发生更改时执行Sub

时间:2017-12-04 11:43:33

标签: excel vba excel-vba combobox

我创建了一个userform,其中是一个comboBox 根据用户选择的结果,新的组合框将显示新的选项以供选择。 以下是我试过的最新测试。

如何制作它以便当用户更改新组合框中的值时,它将执行预制函数/ sub

表格中的代码

Dim WB As Workbook
Dim structSheet As Worksheet
Dim tbCollection As Collection


Private Sub UserForm_Activate()
    Dim ignoreList(3) As String

    ignoreList(0) = "main"
    ignoreList(1) = "configurator"
    ignoreList(2) = "create structure"
    Set WB = Excel.ActiveWorkbook

    For Each sheet In WB.Worksheets
        If Not isInTable(ignoreList, sheet.Name) Then
            supercode_box.AddItem sheet.Name
        End If
    Next
End Sub

Private Sub supercode_box_Change()
    If Not sheetExists(supercode_box.text) Then Exit Sub
    Set structSheet = WB.Worksheets(supercode_box.text)

    'Dim obj As clsControlBox

    topPos = 10
    leftPos = 54
    ID = 1

   ' For ID = 1 To 2
        Set ComboBox = createProductForm.Controls.add("Forms.ComboBox.1")
        With ComboBox
            .Name = "comboBoxName"
            .Height = 16
            .Width = 100
            .Left = leftPos
            .Top = topPos + ID * 18
            .AddItem "test"
            .Object.Style = 2
        End With

        Set tbCollection = New Collection
        tbCollection.add ComboBox

    'Next ID
End Sub

class1模块中的代码

Private WithEvents MyTextBox As MSForms.controlBox

Public Property Set Control(tb As MSForms.controlBox)
    Set MyTextBox = tb
    MsgBox ("did it get here?")
End Property

Public Sub comboBoxName_Change()
    MsgBox ("start working ffs")
End Sub

Public Sub comboBoxName()
    MsgBox ("?? maybe this?")
End Sub

1 个答案:

答案 0 :(得分:0)

判断代码,最简单的方法是在单独的工作表中编写所需的值。

然后检查,是否更改以及是否更改,写入新值并触发您想要的过程。

简而言之,就像这样:

Sub TestMe()

    If Worksheets("Special").Cells(1, 1) = WB.Worksheets(supercode_box.Text) Then
        Call TheSpecificSub
    End If

    Worksheets("Special").Cells(1, 1) = WB.Worksheets(supercode_box.Text)

End Sub