满足条件的Excel VBA停止代码

时间:2019-10-28 20:58:55

标签: excel vba if-statement stoppropagation

我正在努力使我的代码正常工作。

我在excel工作表上有一个按钮,当触发时

  1. 检查必填字段的值为0,如果不是,则显示消息框和结束代码

  2. 检查参考号是否已存在于主选项卡上,是否存在参考,消息框和结束代码

  3. 如果1和2通过,则执行复制并粘贴为3个范围​​的值,然后粘贴消息框。

我尝试了许多选项,但无法使用

    Function Mand() As Boolean
   'checks that mandatory fields have been updated

   If Sheets("INPUT").Range("C11") > 0 Then MsgBox "Mandatory Fields Missing" & vbNewLine & "Changes Not Saved!"
   Mand = True

    End Function


    Function RecEx() As Boolean
    'checks that the reference number does not exisit on the High Level master list

    dup = WorksheetFunction.CountIf(Sheets("High_Level_List").Columns(1), Sheets("INPUT").Range("C17"))
    If dup > 0 Then MsgBox "This Record Exists!!!" & vbNewLine & "If saving an update, use the Save Changes button"
    RecEx = True   

    End Function


    Sub RegisterNewRec()
    ' checks 2 functions, if either are TRUE then exit, otherwise update master

    If Mand Then Exit Sub

        If RecEx Then Exit Sub

    End If

    Dim rng As Range
    Set rng = Sheets("INPUT").Range("AO2:CX2")
    Sheets("High_Level_List").Range("A" & Rows.Count).End(xlUp).Offset(1).Resize(rng.Rows.Count, rng.Columns.Count).Cells.Value = rng.Cells.Value

    'more code that updates master

    MsgBox "Record added to Master"

    End Sub

1 个答案:

答案 0 :(得分:1)

正如我在评论中说的,End If不需要在那里:

If Mand Then Exit Sub
If RecEx Then Exit Sub

^代码的外观

或者,您可以使用:

If Mand Or RecEx Then Exit Sub

您还需要通过包含True块,确保仅在满足上述条件的情况下才将函数设置为End If

Function Mand() As Boolean
If Sheets("INPUT").Range("C11") > 0 Then 
   MsgBox "Mandatory Fields Missing" & vbNewLine & "Changes Not Saved!"
   Mand = True
End If
End Function

Function RecEx() As Boolean
dup = WorksheetFunction.CountIf(Sheets("High_Level_List").Columns(1), Sheets("INPUT").Range("C17"))
If dup > 0 Then 
    MsgBox "This Record Exists!!!" & vbNewLine & "If saving an update, use the Save Changes button"
    RecEx = True
End If
End Function

问题是您将RecExMand设置为true。