workbook.close crashes excel - excel

I'm trying to open an excel file, print it and then close it by clicking on a button.
It opens, it prints, it closes my file and then excel just crashes.
No warning, it justs closes everythting (2 files) and restart by opening the "version 1" of my files.
Workbooks.Open "Thenameofmywb.xlsm"
Workbooks("Thenameofmywb").PrintOut
Application.CutCopyMode = False
Application.Wait (Now + TimeValue("0:00:05"))
Workbooks("Thenameofmywb.xlsm").Close SaveChanges:=True
Here is a bit of my code, I tried the Doevents method and a lot of others small things but none worked.
Maybe you'll be able to help me.

I found it. I don't think it was code related or not in the code I wrote.
The file that I was opening must have been corrupted.
I tested with "clean" files and it worked.
So I copied and pasted informations from the "corrupted" file to a new one and now it runs well.
Now I don't know how they got corrupted but that's for an other time.
Thank you all for your help

You are not making any changes to the file, just accessing it, printing and closing it. So last part should be SaveChanges := false
Also "On Error Resume Next" at the beginning of the sub procedure.

The below code works on my side, using Nathan's idea of using an object.
Sub qqq()
Workbooks.Open "C:\Users\info\Documents\HHH.xlsx"
Set wb = Workbooks(2)
wb.PrintOut
Application.CutCopyMode = False
Application.Wait (Now + TimeValue("0:00:05"))
wb.Close
End Sub

I tried even the following code and it works:
Sub hhh()
Workbooks.Open "C:\Users\info\Documents\HHH.xlsx"
Set wb = Workbooks(2)
wb.PrintOut
'Application.CutCopyMode = False
'Application.Wait (Now + TimeValue("0:00:05"))
wb.Close
End Sub
I commented out 2 lines of code. I am testing with xlsx as a file that needs to be printed. If you are using xlsm, there might be some code there that you have that could be causing an impact. You could still use xlsm but in a way that code from 2 workbooks open at the same time could cause an issue.

Related

Closing Excel via VBA

Long ago I had a macro that would open some workbooks, do some fiddling, then close - all fully automated, called from the commandline so I could batch file it and stick it in windows schedule to run when needed.
I've had call to do it again and of course no longer have access to those files (like four companies ago) so had a bash at recreating them, but stuck on closing excel.
ActiveWorkbook.Close SaveChanges:=True
This works to close the workbooks I'm updating, however, if I use it on the macro containing workbook, it closes the workbook within Excel, but leaves the instance of excel running (with no workbooks).
Application.Quit
This is what I think should be the right command, however this also throws an error:
Run-time error '1004':
Application-defined or object-defined error
However, it's odd. If I just run that command within excel on its own, there's no error, it only errors if the workbook calls the macro containing it.
As it's an auto-launching macro, I have an initial macro in ThisWorkbook that has the Private Sub Workbook_Open() which kicks everything off.
I'd read that Application.Quit can cause this error message when the workbook has an auto-launching macro and it's called from a module, rather than ThisWorkbook, so I moved the Sub QuitExcel() that I created, containing just Application.Quit but still get this error.
The suggested posts from SO when posting this gave a few things to try, like DisplayAlerts=False and saving the workbook, so I updated my quit sub to:
Sub QuitExcel()
Application.DisplayAlerts = False
Application.EnableEvents = False
ThisWorkbook.Save
Application.Quit
ThisWorkbook.Saved = True
End Sub
(and various permutations of that)
However I still persist in getting the same error.
Interestingly, if I click "debug" (rather than end, continue is greyed out) Excel still quits, and doesn't actually go to debugging.
Anyone have experience in what I'm trying to achieve, I just want to kill Excel after it's finished running, from auto-launching a macro?
Answer turned out to be relatively easy, I need to close my workbook before quitting excel and the closing macro can't be in the ThisWorkbook, it has to be in a module (otherwise when the workbook is closed, access to the rest of the code is gone).
So my command ended up being:
Sub QuitExcel()
ActiveWorkbook.Close SaveChanges:=False
Application.Quit
End Sub
Just needed a bit more googling and trial/error.
You should know that VBA code only run in a workbook context ThisWorkBook , that mean when you close it using WorkBook.Close, there will be no code to execute.
So, you only save then use Application.Quit
Do not close the workbook
For Each w In Application.Workbooks w.Save Next w Application.Quit

vba function "sendkeys" does not send anything

It seems that "sendkeys" is only good for turning off your numbers lock. It does not appear to do anything else. I've tried many different ways to simply write random characters to notepad with no success. My only hunch is this ability has been disabled by a recent Windows update as it used to work fine until last week. Below is some example code. Does anyone know how to get it to send keys again?
Public Sub WriteToNotePad()
Dim vReturn As Variant
vReturn = Shell("NotePad.exe", vbNormalFocus) 'open notepad
AppActivate vReturn 'ensure notepad is active
Application.Wait (Now() + TimeValue("00:00:03")) 'wait a few seconds
SendKeys "You should see this in notepad", True
End Sub
I used a computer that didn't get the Office 365 update & the code worked fine. So I'm certain that's the problem. To fix it, I used John Coleman's suggestion to write a VBS file instead & then call that script from the VBA code.
From the above example, change this:
SendKeys "You should see this in notepad", True
To this:
Call Shell("wscript C:\writeToNotepad.vbs", vbNormalFocus)
And the VBS file would be saved in that location with that name & with this content:
Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.SendKeys "You should see this in notepad"

Opening an EXE Application after a timeout with VBA

This is a bit tricky to explain, but let me try.
I have 6 UserForm in a VBA Project.
The execution of the macro will hide each form and show the next one in line.
In the first UserForm, on the click event of the Next button there is some code that modifies the currently opened Excel file, then hides the current UserForm, show the next one AND open saplogon.exe after a 5 second timeout.
It all works perfectly, BUT saplogon doesn't open until after i closed the 6th UserForm. Whereas i want it to open in the second, which is where the code to open the file is at.
I'm not really sure what i'm doing wrong. Following is the code i use in UserForm1.
Application.ScreenUpdating = False
'My Code
UserForm2.Show
Dim sFullPathToExecutable As String
sFullPathToExecutable = "C:\Program Files(x86)\SAP\FrontEnd\SAPgui\saplogon.exe"
Application.Wait (Now + TimeValue("0:00:05"))
Shell sFullPathToExecutable
End Sub
Why isn't the EXE opening at UserForm2?
Thanks!
If by any chance someone else find themselves in a similar situation where you have to open a program in the background and show the next userform without losing focus on excel, Place the shell("location of the .exe") line into your next userform's Activate event:-
Private Sub UserForm_Activate()
Application.Wait (Now + TimeValue("0:00:02"))
Shell "C:\Program Files (x86)\SAP\FrontEnd\SAPgui\saplogon.exe"
End Sub

Excel crashes on opening a module in vba

I am pretty new to macros but I attempted building one, a pretty elaborate one in fact! After the last validation piece that I included in my code, excel crashes every time I try to open the module where i coded most part of my macro. This happens even when i try to save the workbook that contains this macro. I am able to open other modules within this workbook and any other excel workbook. The problem seems to persist only with one particular module after I added an if condition at the beginning of a subroutine. Basically, below is what i tried that I believe makes excel to crash every time I try to do anything with this macro:
Sub Process()
Application.ScreenUpdating = False
Application.DisplayAlerts = False
If ThisWorkbook.Sheets("Main").Range("XFD2").Value <> 2 Then
MsgBox "Create reports first!"
Else
'Lot of other stuff
End If
End Sub
Every time I try to open this module, windows says Microsoft excel stopped working and then i get another pop that leaves me with no other option but to close the program. I have attached the screen shot of the message.
I searched online and got to know such problems arise when a program is installed that would crash with Microsoft program, but I did not install anything new and also checked the add-ins to excel in safe mode, I see no com add-ins.
I would have removed that last condition, but excel does not allow me to open the subroutine. I have invested a lot of time building this macro, any help would be much appreciated!
Your Macro should not be causing Excel to crash, either the way you are saving the file is causing the error or you have a problem with its installation.
And make sure you set those reset ScreenUpdating and DisplayAlerts to true,
Sub Process()
Application.ScreenUpdating = False
Application.DisplayAlerts = False
If ThisWorkbook.Sheets("Main").Range("XFD2").Value <> 2 Then
MsgBox "Create reports first!"
Else
'Lot of other stuff
End If
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub

Too long saving time in Excel via VBA

Some unusal phenomenon started affecting my macro. I have a relatively big (13MB) excel workbook. ThisWorkbook.Save worked just fine. It took like 10 seconds to save the workbook (without any data changes). Now it takes for 2 minutes. Same goes for ThisWorkbook.Close SaveChanges:=True. I am using Excel 2010 on Windows 7.
The strange thing is I can save the workbook manually without any issues, like CTRL+S or using the Save icon in the Excel menu. This way the saving procedure takes less than 10 seconds just as my code used to do it.
The occurence of this unnecessary delay is really bugging me. Do you have any experience with an issue like this? I'm looking for tips to get an approach on the problem.
EDIT:
I've changed to xlsb format as was advised and went a little further with testing. There are some cases when the saving time looks appropiate:
Significant data changes in lots of sheets (48s)
The Save command is triggered from a newly created module without any other changes (5s)
All my charts (150pcs) are deleted (1s). Apparently each chart gives about 1 extra second to the saving time. I know, i should use one dynamic but the damn label bugs... And it was totally fine before!
EDIT 2:
The issue has vanished today. Save command works properly again, saving takes for only a few seconds. Dunno what caused the problem, but I am affraid it will be back and will affect my macro some day again. Excel is definitely quirky!
Since the manual CTRL+S works, I go with the SendKey method until there are better solutions. It does a much faster job than the Save command. Bugs like this are just killing me ...
ThisWorkbook.Activate
SendKeys "^s"
DoEvents
ThisWorkbook.Close
How about this?
Sub Macro1()
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
ThisWorkbook.Save
Application.ScreenUpdating = True
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
End Sub
I had similar issue and been struggling with it for a while. Even for every small files 0.5MB it took almost 1 min to save.
SendKeys doesn't work for me in 100% cases. Sometimes workbook was closed Thisworkbook.Close SaveChanges:=False before SendKeys was able to perform action ("^s"), even after adding Application.Wait Now() + TimeValue("0:00:05").
Somehow it's relating (in my case) to Application.CalculateBeforeSave property. When changed to False workbook saved in couple of seconds.
Dim oWB as Workbook
Set oWB = Workbooks.Open(main_path & file_name, False, False)
oWB.Sheets(1).Calculate
Application.CalculateBeforeSave = False
oWB.Save
Application.CalculateBeforeSave = True
oWB.Close savechanges:=False
set oWB = Nothing

Resources