2016-04-13 28 views
1

enter image description here我有一個工作表中有2個表在那裏。代碼來填充組合框的文本框的值的變化

一個表是組頭,另一個表是控制頭。

在組頭表中,有幾個唯一記錄及其ID。類似非流動資產具有ID NC,流動資產具有ID CA等等。 在控制檯表中,有幾個唯一的記錄以及組頭標識。像薩爾曼和阿米爾有身份證NCA和阿卜杜爾雷曼和拉希姆身份證CA.

當我打開用戶窗體,組頭框組合框填充組頭和組代碼文本框顯示在組合框中選擇的項目的ID。

還有另一個名爲控制頭的組合框。 我想要的是,控制檯組合框將僅填充組標題文本框中存在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 

我無法填充controlhead組合框。

請審查並幫助我。

+0

這是很容易居然但在此之前我發佈一個答案,你可以展示你的表的截圖,這樣我可以檢查代碼之前postin git –

+0

我已張貼表格的圖像... –

回答

0

我的樣本數據

enter image description here

邏輯代碼

  1. 添加表1項combobox1
  2. 在第一個組合框的單擊事件,填充文本框和第二個組合框

在行動

enter image description here

代碼

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 
+0

謝謝你Siddharth ... –