What format must cells have for datarange for combobox in VBA?

202 views Asked by At

When I select a value in ComboBox1, ComboBox2 is automatically filled with data from a specified range. On selecting a value in ComboBox2 a corresponding value will be placed in a TextBox. It appears that when I have only numbers in the ComboBox value the code will not function. If the value consists of letters or numbers AND letters everything works just fine. I tried different formatting of the cells in the range, but no success. Finding an answer on internet is problematic as I don't know the keywords for searching.

Here's my code so far:

Private Sub ComboBox1_Change()
Dim index1 As Integer
Dim cLoc1 As Range
Dim index2 As Integer
Dim cLoc2 As Range
Dim ws As Worksheet
Set ws = Worksheets("Formlists")
index1 = ComboBox1.ListIndex
'index2 = ComboBox2.ListIndex
ComboBox2.Clear
ComboBox3.Clear
    Select Case index1
        Case Is = 0
            With ComboBox2
                For Each cLoc1 In ws.Range("Codelist1")
                    With Me.ComboBox2
                        .AddItem cLoc1.Value
                    End With
                Next cLoc1
            End With                  
        Case Is = 1
            With ComboBox2
                For Each cLoc1 In ws.Range("Codelist2")
                    With Me.ComboBox2
                        .AddItem cLoc1.Value
                    End With
                Next cLoc1
            End With
End Select
End Sub 
Private Sub combobox2_change()
Dim index2 As Integer
Dim ws As Worksheet
Set ws = Worksheets("Formlists")
index2 = ComboBox1.ListIndex
    Select Case index2
        Case Is = 0
            With TextBox4
                For i = 1 To 10
                    If ws.Cells(i + 1, Columns(90).Column).Value = ComboBox2.Value Then
                        TextBox4.Value = ws.Cells(i + 1, Columns(91).Column).Value
                    Else
                        'do nothing
                    End If
                Next i
            End With
        Case Is = 1
            With TextBox4
                For i = 1 To 10
                    If ws.Cells(i + 1, Columns(92).Column).Value = ComboBox2.Value Then
                        TextBox4.Value = ws.Cells(i + 1, Columns(93).Column).Value
                    Else
                        'do nothing
                    End If
                Next i
            End With
End Select
End Sub

Is there a way to let the code/ComboBox accept any inputformat?

Thanks in advance

Rob

1

There are 1 answers

0
Rory On

It appears you just need to coerce the values to strings in the code:

If CStr(ws.Cells(i + 1, 90).Value) = ComboBox2.Value Then

and similarly with the other test. Note there isn't any point in using Columns(90).Column rather than just 90. ;)