【问题标题】:Code to Populate Combobox with the change in Value of Textbox使用文本框值的更改填充组合框的代码
【发布时间】:2016-04-13 21:07:49
【问题描述】:

我有一个工作表,其中有 2 个表格。

一个表是grouphead,另一个表是controlhead。

在 grouphead 表中,有几个唯一记录及其 ID。就像非流动资产有一个 ID NCA,流动资产有一个 ID CA 等等。 在 controlhead 表中,有几个唯一记录以及 grouphead id。就像 Salman 和 Amir 的身份是 NCA,Abdur Rehman 和 Rahim 的身份是 CA。

当我打开用户窗体时,grouphead 组合框会填充 grouphead 并且 groupcode id 文本框显示组合框中所选项目的 id。

还有另一个名为 controlhead 的组合框。 我想要的是,controlhead 组合框将仅填充那些在 grouphead 文本框中具有 id 的值。

到目前为止,我的代码如下:

Private Sub ComboBox1_Change()
    Dim start As String
    Dim start2 As String
    Dim sfind As String
    Dim sfind2 As String
    Dim ws As Worksheet
    Dim tbl As ListObject
    Dim tbl2 As ListObject

    Set ws = Sheets("Summary of Accounts")
    Set tbl = ws.ListObjects("grouphead")
    Set tbl2 = ws.ListObjects("controlhead")

    With Me
        If .ComboBox1.Value <> vbNullString Then
            sfind = .ComboBox1.Value
            start = Application.WorksheetFunction.VLookup(sfind, tbl.DataBodyRange, 2, False)
                .TextBox1 = start
        End If
    End With

    With Me
        If .TextBox1.Value <> vbNullString Then
            sfind2 = .TextBox1.Value
            start2 = Application.WorksheetFunction.VLookup(sfind2, tbl2.DataBodyRange, 2, False)
            .ComboBox2 = start2
        End If
    End With
End Sub

我无法填充控制头组合框。

请查看并帮助我。

【问题讨论】:

  • 其实很简单,但是在我发布答案之前,你能显示你的表格截图,以便我可以在发布 git 之前检查代码
  • 我已经发布了桌子的图片...

标签: excel vba


【解决方案1】:

我的样本数据

代码逻辑

  1. 将表 1 项添加到组合框 1
  2. 在第一个组合框的点击事件中,填充文本框和第二个组合框

行动中

代码

Dim tblGH As ListObject
Dim tblCH As ListObject

'~~> Populate combobox1 in userform init event
Private Sub UserForm_Initialize()
    Dim ws As Worksheet

    Set ws = Sheets("Summary of Accounts")

    Set tblGH = ws.ListObjects("grouphead")
    Set tblCH = ws.ListObjects("controlhead")

    For i = 1 To tblGH.DataBodyRange.Rows.Count
        ComboBox1.AddItem tblGH.DataBodyRange.Cells(i, 1)
    Next
End Sub

'~~> The click event
Private Sub ComboBox1_Click()
    Dim r As Long

    r = ComboBox1.ListIndex

    If r = -1 Then Exit Sub

    '~~> Add to txtbox
    TextBox1.Text = tblGH.DataBodyRange.Cells(r + 1, 2)

    '~~> Add to 2nd Combo
    PopulateCombo
End Sub

Sub PopulateCombo()
    ComboBox2.Clear

    For i = 1 To tblCH.DataBodyRange.Rows.Count
        If tblCH.DataBodyRange.Cells(i, 1) = TextBox1.Text Then _
        ComboBox2.AddItem tblCH.DataBodyRange.Cells(i, 2)
    Next
End Sub

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-07
    • 2014-05-03
    相关资源
    最近更新 更多