我怎样才能使一个用户表单完成另一个?

时间:2019-05-17 18:11:32

标签: excel vba

我有一个用户窗体,带有两个组合框。其中一个包含零件号,另一个包含零件说明,例如:

部件号: 01982391823

说明: 5/8“ Festo阀门

它们两个都有另一个工作表(数据库)中的项目。

我想要做的是,如果我将代码放入代码组合框中,则另一个向我显示相应的描述,反之亦然(因为它们大约有400项)。有可能吗?

1 个答案:

答案 0 :(得分:0)

尝试下面的代码,我假设您的零件号位于A列中,说明位于B列中。

组合框部件名称:cbo_part, ComboBox描述名称:cbo_desc

Dim mySh As Worksheet


Private Sub cbo_desc_Change()

If cbo_desc.Value <> "" Then
    'LOOP THRU ALL THE DATABASE AND LOOK FOR THE DESC ROW NUMBER AND GET THE PART
    For a = 2 To mySh.Range("B" & Rows.Count).End(xlUp).Row
        If CStr(mySh.Range("B" & a).Value) = cbo_desc.Value Then
            cbo_part.Value = mySh.Range("A" & a).Value
            Exit For
        End If
    Next a
End If
End Sub

Private Sub cbo_part_Change()

If cbo_part.Value <> "" Then
    'LOOP THRU ALL THE DATABASE AND LOOK FOR THE PART ROW NUMBER AND GET THE DESC
    For a = 2 To mySh.Range("A" & Rows.Count).End(xlUp).Row
        If CStr(mySh.Range("A" & a).Value) = cbo_part.Value Then
            cbo_desc.Value = mySh.Range("B" & a).Value
            Exit For
        End If
    Next a
End If
End Sub

Private Sub UserForm_Initialize()

Set mySh = ThisWorkbook.Sheets("Sheet1") 'name of your worksheet database

'ADD ITEMS TO COMBOBOX PART
With cbo_part
    'Loop thru all the parts and add to the combobox part
    For a = 2 To mySh.Range("A" & Rows.Count).End(xlUp).Row
        cbo_part.AddItem mySh.Range("A" & a).Value
    Next a
End With


'ADD ITEMS TO COMBOBOX DESCRIPTION
With cbo_desc
'Loop thru all the description and add to the combobox description
    For b = 2 To mySh.Range("B" & Rows.Count).End(xlUp).Row
        cbo_desc.AddItem mySh.Range("B" & b).Value
    Next b
End With

End Sub