您能提示我如何使此类代码更优雅吗?
将来我需要更多此类查询,并且我想更专业地进行。
谢谢!
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
答案 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
答案 3 :(得分:1)
以下内容如何:
If Case = "V" Then
ElseIf Case = "K" Then
ElseIf Case = "A" Then
...
End If