Adding new VBA userform combobox values to a sheet

I'm still fairly new to VBA so I am struggling to work this out... I have a Userform with a variety of inputs including some comboboxes using lists from the excel sheet. What I would like to do is if a user adds a new value to that combobox, upon saving the form it should check the list and if the value doesn't exist then add it to the end of the list. This is what I've tried to put together so far from things I have found online (once I have this working I will then be putting it in a loop to cover multiple comboboxes):
Dim ws As Worksheet: Set ws = Sheets("Lists")
Dim EmptyRow As Long
Dim FoundVal As Range
EmptyRow = ws.Cells(ws.Rows.Count, "D").End(xlUp).Row + 1
If CoBJobList1.ListIndex > -1 Then
Set FoundVal = ws.Range("D2:D" & EmptyRow).Find(CoBJobList1.Value)
If Not FoundVal Is Nothing Then
'Do Nothing
Else
ws.Range("D" & EmptyRow).Value = CoBJobList1.Value
End If
End If
Answer
You want to check for -1 not anything above -1.
Dim ws As Worksheet: Set ws = Sheets("Lists")
Dim EmptyRow As Long
EmptyRow = ws.Cells(ws.Rows.Count, "D").End(xlUp).Row + 1
If CoBJobList1.ListIndex = -1 Then
ws.Range("D" & EmptyRow).Value = CoBJobList1.Value
End If
I removed the .Find
as well, it knows the placement in the list even if they typed the value and didn't actually select it.
You may need some data integrity if you're worried about typos, for example if your values are numerical and the values in the list are [0, 1, 2, 3] and they type in "03" it will add another "3" to the list.
Enjoyed this article?
Check out more content on our blog or follow us on social media.
Browse more articles