通过更改值影响不同的过程

Affecting different Procedures by changing values

我有这个调用其他程序的主程序。但是在两个地方,我需要检查所有值是否正确。如果不是,我希望这个主程序退出。我想要做的是检查我的子过程中的值,如果它们不正确,将 exitall 更改为 true,这将导致子过程停止。问题是,我相当确定如果我在我的子程序中说将 exitall 的值更改为 true,它不会影响我的主程序。

我的问题是,如果在我的子程序中更改了 exitall,我该如何使它在我的主程序中更改?

谢谢。

Sub Allstepstogether()
 Dim r As Integer
 Dim exitall As Boolean
 Dim answer As Variant
 Dim hda As Boolean
 Dim wdfh As Variant

 hda = False
 exitall = False

 Call Clean

 For Each cell In ThisWorkbook.Sheets("Heyaa").Range("C2:C15")
     If Weekday(Date) = vbMonday Then
         If CDate(cell.Value) = Date - 3 
            hda = True
            wdfh = cell.Offset(0, 1).Value
         End If
     Else
         If CDate(cell.Value) = Date - 1 Then
             hda = True
             wdfh = cell.Offset(0, 1).Value
         End If
     End If
 Next cell

Call step4

 r = Application.WorksheetFunction.CountA(ThisWorkbook.Sheets("BlaCheck").Range("A1:A150"))
 If r <> 100 Then
     answer = MsgBox("Data not yet uploaded, try again later.", vbOKOnly)
     Exit Sub
 Else
     Call step5
     If exitall = True Then
         Exit Sub
     Else
         Call Step7alloptions
         Call step8
         Call Timetocheck
         If exitall = True Then
             Exit Sub
         Else
             Call Step9
             Call Step10
             Call Step11
         End If
     End If
 End If
 end sub

步骤 5 的一部分,应该将 exitall 更改为 true,从而在不正确时停止执行主程序。

  sub Step5
  dim exitall as boolean
  dim lr as integer

  '....
  'code
  '....

  lr = Application.WorksheetFunction.CountA(ThisWorkbook.Sheets("BlaCheck").Range("A1:A500"))
  If lr > 100 Then
     answer = MsgBox("Ups, It did not run correctly, this code execution will be terminated", vbOKOnly)
     exitall = True
     Exit Sub
  End If
  end sub

选项 1 是在全局范围内声明 exitall

Dim exitall As Boolean    '<--Add this at the top of the module.

Sub Allstepstogether()
    Dim r As Integer
    'Dim exitall As Boolean  '<--Remove this from all your Subs.

更好的方法是将您的 Subs 更改为 Functions that return a Boolean 成功并进行测试。请注意,您也不必在 If 条件退出后使用 Else - 这应该会大大降低缩进级别:

转换子:

Function Step5() As Boolean
    Dim lr As Integer

    '....
    'code
    '....

    lr = Application.WorksheetFunction.CountA(ThisWorkbook.Sheets("BlaCheck").Range("A1:A500"))
    If lr > 100 Then
       answer = MsgBox("Ups, It did not run correctly, this code execution will be terminated", vbOKOnly)
       Exit Function
    End If
    Step5 = True
End Function

调用代码:

Sub Allstepstogether()
    '[Snip]
    r = Application.WorksheetFunction.CountA(ThisWorkbook.Sheets("BlaCheck").Range("A1:A150"))
    If r <> 100 Then
        answer = MsgBox("Data not yet uploaded, try again later.", vbOKOnly)
        Exit Sub
    End If
    If Not Step5 Then Exit Sub
    Step7alloptions
    step8
    If Not Timetocheck Then Exit Sub
    Step9
    Step10
    Step11
End Sub