I tested the following code in Excel 2016. But I encounter an
error message of 1004
and the code does not work.
Error line:
Me.TextBox1.Text = Application.WorksheetFunction.VLookup(Me.ComboBox1.Value, xRg, 2, False))
Private Sub UserForm_Click()
Dim xRg As Range
Private Sub UserForm_Initialize()
Set xRg = Worksheets("Sheet1").Range("A2:B8")
Me.ComboBox1.List = xRg.Columns(1).Value
End Sub
Private Sub ComboBox1_Change()
Me.TextBox1.Text = Application.WorksheetFunction.VLookup(Me.ComboBox1.Value,
xRg, 2, False)
End Sub
It seems that xRg
is declared outside of the scope of the ComboBox1_Change
event. Thus, the Combobox1_Change()
does not access it. Try to declare it within:
Private Sub ComboBox1_Change()
Dim xRg As Range
Set xRg = Worksheets("Sheet1").Range("A2:B8")
Me.TextBox1.Text = Application.WorksheetFunction.VLookup(Me.ComboBox1.Value, _
xRg, 2, False)
End Sub
Answer:
As mentioned by @Vityata here, you will need to assign the xRg variable within your current code block as it has no reference to it.
As an addition to that though, I would advise ditching the vlookup application function in place of assignment by the combobox index: Me.ComboBox1.ListIndex
and use that as the reference for the row in xRg:
Me.TextBox1.Value = xRg.Cells(Me.ComboBox1.ListIndex + 1, 2).Value
The ComboBox.ListIndex property is a 0 based array so I have added 1 on to get the proper row assignment.
Tags: excelexcel, text, vba