【问题标题】:Limit to ElseIf Conditions?仅限于 ElseIf 条件?
【发布时间】:2017-02-15 14:30:09
【问题描述】:

所以我有一些 VBA 代码,旨在根据单元格中的值处理一些事情。读取单元格中的值并相应地运行代码。这没有问题。

If Target.Value = "something" Then
End If
ElseIf Target.Value = "something2" Then
End If
ElseIf Target.Value = "something3" Then
End If
ElseIf Target.Value = "something4" Then
End If

效果很好,但是如果我添加一个额外的 ElseIf 条件,我会得到“Else without If”的编译器错误。在第五个条件下将 ElseIf 更改为 Else 并不能解决问题。我的问题是我可以运行的 ElseIf 条件的数量是否有限制?我实际上只需要第五个就可以完全完成我正在尝试做的事情。我肯定条件内的代码没有错误。

【问题讨论】:

  • “这没有问题” 什么?确定????
  • Ahhhh 就是这样......代码有点乱,所以我假设最后一个 ElseIf 语句的 EndIf 在所有其他语句中,但事实并非如此。我的错误应该抓住那个。
  • 我可以运行的 ElseIf 条件的数量是否有限制 - 没有(模块将在 10K 行之后停止编译)。限制是你可以在心里记下多少。在某一时刻,您应该考虑使用 Select Case 块,如果可能的话,在另一时刻,您会考虑为每个案例设置一个单独的过程,也许还有一个运行适当方法的 CallByNameApplication.Run 调用 - 然后你可以Dictionary 键入 Target.Value 值并使用过程名称进行赋值,然后转到 Application.Run strategies(Target.Value),使其成为 1-liner!

标签: vba excel if-statement


【解决方案1】:

The End If 只在最后:

If Target.Value = "something" Then
    'Do something
ElseIf Target.Value = "something2" Then
    'Do something
ElseIf Target.Value = "something3" Then
    'Do something
ElseIf Target.Value = "something4" Then
    'Do something
End If

【讨论】:

  • 是的,我现在明白我的错误了,哈哈。还是新手,谢谢您的回复!
【解决方案2】:

您当然应该“升级”您的多个ElseIf 并使用Select Case

这会让您在未来更轻松地实现更多场景。

Select Case Target.Value
    Case "something"
        ' code 1 here

    Case "something2"
        ' code 2 here

    Case "something3"
        ' code 3 here

    Case "something4"
        ' code 4 here

    Case "something5", "something6" ' <-- replaces using another If with And
        ' code 5 here

    ' Case ....

End Select

【讨论】:

  • 好的,我去看看!感谢您的回复!
  • @GingerbreadPK 一旦你尝试Select Case,你将永远不会回去:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-04-09
  • 2017-03-09
  • 2012-02-05
  • 2021-07-11
  • 2015-09-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多