消除多个Elseif语句 [英] Eliminating multiple Elseif statements

查看:54
本文介绍了消除多个Elseif语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图保持我的代码整洁,尤其是在用户窗体中使用组合框时,可能会有很多if Elseif语句.应该有一种更简单的方法,使仅一个组合框就没有多页代码?

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

您可以想象这可以变成20个名称的长代码,假设具有3-4个下拉菜单.有什么(可接受/已知的)方法可以简化这一过程?

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?

推荐答案

我会使用以下内容:

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

这篇关于消除多个Elseif语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆