Click here to Skip to main content
15,896,063 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi All,

I have created one sales related form.
the fields are like Item, price all these data stored in excel sheet.
When select Item in userform the relavent price textbox value need to get price by default how to do this.
Posted

1 solution

Steps to do:

  1. Add new shee and change its name to "Data"
  2. Lets A1:B1 range will be the headers: Item and Price respectively
  3. Add sample data
  4. Go to VBA code editor (ALT+F11)
  5. Add module (Tools->Insert->Module)
  6. Copy and paste below code
  7. VB
    Option Explicit
    'loads data into 2 columns listbox from desired range
    Sub Load2Columns(ByRef oLst As MSForms.ListBox, ByRef wsh As Worksheet, Optional ByVal sFirstColumn As String = "A", Optional ByVal iFirstRow As Integer = 2)
    Dim i As Integer
    
    With oLst
        Do While wsh.Range(sFirstColumn & iFirstRow) <> ""
            .AddItem ""
            i = .ListCount - 1
            .Column(0, i) = wsh.Range(sFirstColumn & iFirstRow)
            .Column(1, i) = wsh.Range(sFirstColumn & iFirstRow).Offset(ColumnOffset:=1)
            iFirstRow = iFirstRow + 1
        Loop
    End With
    
    End Sub

  8. Add UserForm (Tools->Insert->UserForm
  9. From ToolBox add
  10. <il>
    • one ListBox

    • one TextBox

    • two Labels

    • one Button


  11. Copy and paste below code:
  12. VB
    Option Explicit
    
    Private Sub CommandButton1_Click()
    Unload Me
    End Sub
    
    Private Sub ListBox1_Change()
    Me.TextBox1 = Me.ListBox1.List(Me.ListBox1.ListIndex, 1)
    End Sub
    
    Private Sub UserForm_Initialize()
    
    Load2Columns Me.ListBox1, ThisWorkbook.Worksheets("Data")
    With Me.ListBox1
        .ColumnCount = 2
        .ColumnWidths = ";0"
        .ListIndex = 0
    End With
    
    End Sub

  13. That's all! Now, when you change selection for ListBox, the price will be loadded to the TextBox


Here[^] you can download an example.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900