1

I need some help with Excel VBA (2010 on windows 7). What I'm trying to do is close Excel and then shutdown the pc. The code I have is:

Declare Function ExitWindowsEx& Lib "User32" (ByVal uFlags As Long, ByVal dwReserved AS Long)
Global Const EWX_LOGOFF = 0
Global Const EWX_FORCE = 4

....Main Code Here ....

Application.DisplayAlerts = False
Application.Quit

Action = ExitWindows(EWX_LOGOFF or EWX_FORCE, 0)

Intermittently I get the following error:

Cannot Quit Microsoft Excel

The machine still logs off though, which is what I want so it's not a major issue. I would just like to exit cleanly. I've kept EWX_FORCE as I don't want to be prompted by windows. Any suggestions?

Jon Crowell
  • 21,695
  • 14
  • 89
  • 110
rockOn123
  • 45
  • 1
  • 1
  • 7

1 Answers1

0

Missing DoEvents after Application.Quit maybe? Include that so that Excel gets enough time to close else you will get an error. BTW this worked for me.

Also if any workbook/workbooks is/are opened then then it is a good idea to close it/them with/without saving code as you might loose data.

Public Declare Function ExitWindowsEx Lib "user32" (ByVal dwOptions As Long, _
ByVal dwReserved As Long) As Long

Public Const EWX_LogOff As Long = 0
Public Const EWX_SHUTDOWN As Long = 1
Public Const EWX_REBOOT As Long = 2
Public Const EWX_FORCE As Long = 4

Sub Sample()
    '
    '~~> Main Code Here
    '
    Application.DisplayAlerts = False
    Application.Quit

    DoEvents

    ExitWindowsEx EWX_LogOff Or EWX_FORCE, &HFFFF
End Sub
Siddharth Rout
  • 147,039
  • 17
  • 206
  • 250
  • When i add Do Events i am now not logged off. – rockOn123 Jul 13 '12 at 08:26
  • The above code is tried and tested :) If you are not getting logged off then there is something which is preventing the system from logging off. And hence you were getting the error when you tried forcing a Log Off. `DoEvents` gives windows time to finish whatever it is doing before it can log off. You may also check for CPU activity when you issue the above command. – Siddharth Rout Jul 13 '12 at 11:51
  • When I run this code, as soon as vba hits the `Application.Quit` line, Excel shuts down (as expected), consequently, the subsequent lines aren't processed. The only way I can get this to work for me is to comment out the `Application.Quit` line, then the `DoEvents` and `ExitWindowsEx` lines do get processed. What am I missing here? – DaveU Sep 29 '15 at 17:57
  • What happens when you move `Application.Quit: DoEvents` after `ExitWindowsEx` line? – Siddharth Rout Sep 29 '15 at 18:00
  • It seems to work OK then, but I'm not sure if ExitWindowsEx is closing Excel before it gets to the Application.Quit line. Also, if I comment out the ExitWindowsEx line, and put a break point opposite DoEvents, the Application.Quit line shuts down Excel before getting to the DoEvents line. – DaveU Sep 30 '15 at 02:12