Search code examples
vbams-accesscombobox

How to set value of combobox with two columns?


I am using an unbound form. I have a combobox called PO_Number, and a combobox called Vendor_Name. In an after update event for the PO_Number, I use the PO_Number and get the Vendor_Name. In VBA, I try to set the value of the combobox like so:

Vendor_Name.Value = rs!Vendor_Name

It runs but the text does not show up in the combobox.

How can I set the value of a combobox?

After Update event:

Private Sub PO_Number_AfterUpdate()

On Error GoTo ErrorHandler

Dim sql As String
Dim rs As DAO.Recordset
    
sql = "SELECT v.Vendor_Name, p.PO_Date, p.Description FROM PO as p INNER JOIN Vendor as v ON p.Vendor_Number = v.Vendor_Number WHERE p.PO_Number = " & PO_Number.value
    
Set rs = CurrentDb.OpenRecordset(sql)
    
If Not rs.EOF Then
    rs.MoveFirst
        
    Vendor_Name.Value = rs!Vendor_Name
    PO_Date.value = rs!PO_Date
    Description_Tb.value = rs!Description
End If
    
Exit Sub
    
ErrorHandler:
    
    Err.Raise Number:=Err.Number, Description:=Err.Description
    Exit Sub

End Sub

I looked through several answers, all of which were for C# or VB.Net.

EDIT:
I considered using a textbox for Vendor Name, but I need the combobox because the user needs to select a different vendor.

I also realized there are two columns to my Vendor_Name combobox. The first stores the Vendor_Number, the second stores the Vendor_Name. The bound column is set to 1 (Vendor_Name).

How can I set the value of the combobox with two columns?

I would like to set it like so:

Vendor_Name.Column(0) = rs!Vendor_Number
Vendor_Name.Column(1) = rs!Vendor_Name

but it gives me:

Run time error 424.
Object required


Solution

  • Source of issue is misunderstanding BoundColumn property. BoundColumn is not zero-based.

    If combobox RowSource is SELECT Vendor_Number, Vendor_Name FROM Vendors; and BoundColumn is 1 then it is looking at Vendor_Number, not Vendor_Name.

    Column Index is zero-based. So Column(0) refers to first column.

    Need to set combobox Value property with Vendor_Number then with ColumnWidths set as 0";1", associated Vendor_Name will display.

    Use BOUND form and BOUND controls and less VBA will be needed and a lot of these complications will go away.