从Excel中的Combobox返回文本框中的值

时间:2016-04-20 15:28:14

标签: excel vba combobox textbox

我正在寻找最直接的方法来返回三个文本框中的值,基于Userform中组合框的选择。

我有一个名为'TPIDLookup'的工作表,它包含4列; TPID,分公司,公司编号和MQ名称。我已经为所有四列设置了范围,现在我只需要从Combobox中选择TPID时显示Branch Plant,Company和MQ Name的值。然而,当我在Excel中执行此操作时,我迷失了,尽管我很熟悉如何在Access中完成此操作。

如果有帮助,这是我用来生成组合框列表的代码:

Set WS = Worksheets("TPIDLookup")
For Each TPID In WS.Range("TPID")
With Me.cmbTPID
.AddItem TPID.Value
End With
Next TPID

我对网络的研究让我更加困惑,我确信有一种死的直接方式可以做到这一点。我不是程序员,我是VBA的新手,但是任何帮助都会非常感激,因为这是我完成表格的最后一步。

非常感谢,

约翰。

2 个答案:

答案 0 :(得分:1)

为cmbTPID组合框创建一个组合框更改事件并使用此代码。用实际名称替换文本框名称和命名范围名称:

Private Sub cmbTPID_Change()

    Dim ws As Worksheet
    Dim rFound As Range

    If Me.cmbTPID.ListIndex = -1 Then
        'Nothing selected, or user manually typed an invalid entry
        'Clear textboxes
        Me.txtBranch.Value = vbNullString
        Me.txtCompanyNo.Value = vbNullString
        Me.txtMQName.Value = vbNullString
    Else
        'Valid TPID selected
        'Find it and populate the textboxes
        Set ws = ActiveWorkbook.Sheets("TPIDLookup")
        Set rFound = ws.Range("TPID").Find(Me.cmbTPID.Text, , xlValues, xlWhole)
        If Not rFound Is Nothing Then
            Me.txtBranch.Value = Intersect(ws.Range("Branch"), rFound.EntireRow).Value
            Me.txtCompanyNo.Value = Intersect(ws.Range("CompanyNo"), rFound.EntireRow).Value
            Me.txtMQName.Value = Intersect(ws.Range("MQName"), rFound.EntireRow).Value
        End If
    End If

End Sub

答案 1 :(得分:0)

你可以试试这个

这里是您的主要"子代码摘录与您的问题相关

Option Explicit

Public TPIDRng As Range, branchRng As Range, companyRng As Range, MQRng As Range

Sub main()

Set TPIDRng = GetColumnUsedRange(Worksheets("TPIDLookup"), "A")
Set branchRng = GetColumnUsedRange(Worksheets("TPIDLookup"), "B")
Set companyRng = GetColumnUsedRange(Worksheets("TPIDLookup"), "C")
Set MQRng = GetColumnUsedRange(Worksheets("TPIDLookup"), "D")

With UserForm1 ' change it to whatever name your actual UserForm has
    .ComboBox1.List = Application.Transpose(TPIDRng)
    .Show
End With
Unload UserForm1

End Sub

Function GetColumnUsedRange(sht As Worksheet, col As String)

With sht
    Set GetColumnUsedRange = .Range(.Cells(1, col), .Cells(.Rows.Count, col).End(xlUp))
End With
End Function

以及UserForm代码窗格中的相应代码

Private Sub ComboBox1_Change()

With Me
    If .ComboBox1.ListIndex = -1 Then
        .TextBoxBranch.Text = ""
        .TextBoxCompany.Text = ""
        .TextBoxMQ.Text = ""
    Else
        .TextBoxBranch.Text = branchRng.Cells(.ComboBox1.ListIndex + 1, 1).Value
        .TextBoxCompany.Text = companyRng.Cells(.ComboBox1.ListIndex + 1, 1).Value
        .TextBoxMQ.Text = MQRng.Cells(.ComboBox1.ListIndex + 1, 1).Value
    End If
End With

End Sub

Private Sub CommandButton1_Click()
    Me.Hide
End Sub

根据您的需要更改名称(范围,Userform,TextBoxes和Combobox)