其他声明混淆

时间:2018-03-02 23:34:27

标签: excel vba excel-vba

If trigger = "Reconcile" Then
    If InStr(XXlist, checkmi) > 0 Then
          If checkmi = "XX1000" Then
            a = a + 1
            Call XX1000Check(location, a, checkmi)
          End If
          If checkmi = "XX1001" Then
            Call XX1001Check(location, checkmi)
          End If
          Else: Call SenseCheck(location, location2, location7, checkmi)
    End If
End If

我希望我的代码检查Checkmi是否等于其中一个硬编码(XX1000,XX1001),然后调用相应的VBA代码。但是,如果没有针对该特定代码的特定VBA模块,我希望它调用泛型SenseCheck。目前,如果初始条件SenseChec错误,它会执行If InStr(XXlist, checkmi) > 0 k,这不是我想要的。我并不完全确定如何解决这个问题。

2 个答案:

答案 0 :(得分:1)

您已经通过以下If终止了End If声明:

If checkmi = "XX1001" Then
    Call XX1001Check(location, checkmi)
End If '<~~ termination point

您有一个开放式If声明,其中您放置了Else声明。

If InStr(XXlist, checkmi) > 0 Then
      If checkmi = "XX1000" Then
        a = a + 1
        Call XX1000Check(location, a, checkmi)
      End If
      If checkmi = "XX1001" Then
        Call XX1001Check(location, checkmi)
      End If '<~~ termination point as pointed above
      Else: Call SenseCheck(location, location2, location7, checkmi)
End If '<~~ termination point

因此Else语句将与最顶层的非终止 If语句相关联。
这是您的第一个If声明If InStr(XXlist, checkmi) > 0 Then

<强> EDIT1: 要更正代码,请在终止整个Else语句之前添加If语句,并使用ElseIf合并,但如果您有更多条件,则需要使用Select Case

If InStr(XXlist, checkmi) > 0 Then
    If checkmi = "XX1000" Then
        a = a + 1
        Call XX1000Check(location, a, checkmi)
    ElseIf checkmi = "XX1001" Then '<~~ incorporate ElseIf statement
        Call XX1001Check(location, checkmi)
    Else '<~~ transfer the Else statement here
        Call SenseCheck(location, location2, location7, checkmi)
    End If
End If

答案 1 :(得分:0)

扩展给定的答案,只是为了补充一点,你可以考虑通过为&#34; XX1000&#34;采用相同的子码来增强代码并改善其维护。和&#34; XX1001&#34; checkmi

这通过&#34;可选&#34;子/函数可以具有的唯一要求,它们必须保留为签名中的最后一个

例如:

Sub XX100XCheck(checkmi As String, location As Long, Optional a As Variant)

需要传递前两个参数,并将第三个参数作为可选参数。并通过声明Variant类型的后者,您可以检查它是否已经实际传递:

Sub XX100XCheck(checkmi As String, location As Long, Optional a As Variant)

    If Not IsMissing(a) Then 'if "optional" 'a' parameter has actually been passed
        ' here place the code to process "optional" 'a' parameter
    End If

    '... rest of your code to handle "fixed" parameters

End Sub

以便您的问题代码为:

Select Case checkmi
    Case "XX1000"
        a = a + 1
        XX100XCheck checkmi, location, a ' call XX100Check sub passing all kind of parameters ("fixed" and "optional")

    Case "XX1001"
        XX100XCheck checkmi, location ' call the same sub as above, but now you're not passing it the "optional" a parameter

    Case Else
        SenseCheck(location, location2, location7, checkmi)
End Select

您可以使用(并维护)仅一个子(即XX100XCheck())而不是两个(即XX1000Check()XX1001Check()

当然,这可能不会被视为强制编码模式,因为它可能与另一个&#34;良好实践&#34;一个要求简单和简单的例程与#34; all-in-one&#34;那些

所以这是一个平衡问题(一如既往),我的建议是从您的代码中猜测两个XX...Check()潜艇之间的差异很小