如何简化许多“ If Then Else”查询?

时间:2019-12-13 12:34:37

标签: vba if-statement

您能提示我如何使此类代码更优雅吗?

将来我需要更多此类查询,并且我想更专业地进行。

谢谢!

       If Case = "V" Then
            Case Is = "Sal"
        Else
            If Case = "K" Then
                Case Is = "Dep"
            Else
                If Case = "A" Then
                    Case Is = "Auf"
                Else
                    If Case = "M" Then
                        Case Is = "Mon"
                    Else
                        If Case = "T" Then
                            Case Is = "Tec"
                        Else
                            If Case = "W" Then
                                Case Is = "Ver"
                            Else
                                If Case = "B" Then
                                    Case Is = "Ber"
                                Else
                                    If Case = "P" Then
                                        Case Is = "Ver"
                                    Else
                                        GoTo GoNext
                                    End If
                                End If
                            End If
                        End If
                    End If
                End If
            End If
        End If

4 个答案:

答案 0 :(得分:4)

使用Select Case


Sub test()

Dim strCode     As String
Dim strVal      As String

strCode = "B"

Select Case strCode
    Case "A"
        strVal = "Jan"
    Case "B"
        strVal = "Feb"
    Case "C"
        strVal = "Mar"
    Case Else
        strVal = "No match found"
End Select

End Sub

答案 1 :(得分:4)

使用Select Case ... End Select

但是您需要声明一个变量,让我们说x作为引用

Dim x as String, y as String

'Alocate value to the `x` variable. In any whey. Then:

Select Case x
   Case "V": y = "Sal"
   Case "K": y = "Dep"
   Case "A": y = "Auf"

   ' and so  on...

   Case Elxe: y = "Whatever..."   
End Select

最后,您根据y获得了x值...

答案 2 :(得分:2)

通常,将多个if简化为一个字典/哈希表/对象。

Dim variablename
Set variablename = CreateObject("Scripting.Dictionary")
variablename.Add ("V", "Sal")
variablename.Add ("K", "Dep")
....
variablename.Add ("P", "Var")

按如下所示获取变量

ans = 'Nothing' 
if variablename.exists("P") then 
    ans = variablename("P")
    Rem ans = variablename.item("P") ?
    Rem Equals "Var"
end if     

另请参见https://excelmacromastery.com/vba-dictionary/

答案 3 :(得分:1)

以下内容如何:

  If Case = "V" Then

  ElseIf Case = "K" Then

  ElseIf Case = "A" Then

  ...

  End If