Eliminating multiple Elseif statements

孤街醉人 提交于 2021-01-28 00:15:14

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!