问题
Im trying to keep my code clean and especially using Comboboxes in userforms there can be a lot of if Elseif statements. There should be an easier way to not have multiple pages of code for just one combobox is there?
Example of how it is done now:
Sub Example()
Dim Variable as String
If Combobox1.Value = "Option1" Then
Variable = "Name1"
Elseif Combobox1.Value = "Option2" Then
Variable = "Name2"
Elseif Combobox1.Value = "Option3" Then
Variable = "Name3"
Elseif Combobox1.Value = "Option4" Then
Variable = "Name4"
Else Variable = "Name5"
End if
End Sub
As you can imagine this can become a LONG code for 20 names, imagine having 3-4 dropdown menu's. Is there any (acceptable/known) way of simplifying this?
回答1:
I would use something like this:
Sub Example()
Dim arr, res
Dim Variable as String
arr = Array(Array("Option1", "Name1"), _
Array("Option2", "Name2"), _
Array("Option3", "Name3"), _
Array("Option4", "Name4"))
res = Application.VLookup(Combobox1.Value, arr, 2, 0)
If Not IsError(res) Then
Variable = res
Else
Variable = "Name5"
End If
End Sub
来源:https://stackoverflow.com/questions/23119863/eliminating-multiple-elseif-statements