Question : Public variable persistence in Excel VBA

I am developing an Excel workbook that can either be run in the normal way frm Explorer, or instantiated from an external application which then posts data into it. In the latter case, I need to intercept and prevent attempts to close Excel. Under these conditions, the external app can close Excel by calling a macro DoQuit() which will exit the spreadsheet.

DoQuit is declared in a module modPublic and looks like this:

Public Sub DoQuit()
On Error GoTo Err1
  ' Unconditionally close Excel
  bRequestQuit = True
  If Not ThisWB Is Nothing Then
    ThisWB.Saved = True
  End If
  Application.Quit
Err1:
  ' display any errors
  MsgBox Err.Description
End Sub

I have also created a custom event handler in ThisWorkbook, as Application.Quit triggers a Close event:

Private Sub Workbook_BeforeClose(Cancel As Boolean)
On Error GoTo Err1
  If Not bStandalone Then
    If Not bRequestQuit Then
      If bDebugMode Then
        MsgBox "Trapped attempt to close Excel!"
      End If
      Cancel = True
    End If
  End If
Err1:
  ' silently handle any errors
End Sub

The variables bStandalone and bRequestQuit control what happens when Workbook_BeforeClose() runs and are declared as public in modPublic.

If I put a watch on these variables when testing DoQuit, I can see bRequestQuit is set to true. When I step to Application.Quit I can see what happens in Workbook_BeforeClose() if I put a breakpoint in there, but the watch now shows bRequestQuit is set to false, Cancel is set to true and the app does not exit as desired.

Can anybody explain how a public variable can change its value "by itself" in this way?

Answer : Public variable persistence in Excel VBA

The Application.Quit seems to clear the variable. Move it to the ThisWorkbook module and use:

Public Sub DoQuit()
On Error GoTo Err1
 ' Unconditionally close Excel
  ThisWorkbook.bRequestQuit = True
 If Not ThisWB Is Nothing Then
   ThisWB.Saved = True
 End If
 Application.Quit
Err1:
 ' display any errors
 MsgBox Err.Description
End Sub

and you should probably do the same with the other variables.


Random Solutions  
 
programming4us programming4us