Macro-Enabled File Stops Working And Crashes When Any Action Taken - excel

So this is strange to me, but I have a macro-enabled excel 2016 file. The only macro in the file is a BeforeSave event, which is stored in ThisWorkbook. After using the blank file once or twice, it gets to the point where opening the file and doing anything at all, like clicking File or Developer or entering data, causes excel to "Stop Working" and close.
Below is the BeforeSave event which is the only macro in this file (there are no modules or userforms, nothing else in ThisWorkbook).
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Application.EnableEvents = False
Cancel = True
ThisWorkbook.Sheets("Pending").Columns(9).NumberFormat = "#"
ActiveWorkbook.Save
Application.EnableEvents = True
End Sub
This basic macro event will work perfectly for a few times. Then after some data is in the file, the next time it is opened the issue will occur. This is the only excel file that experiences this crash, I can still open the original backup file with this macro that does not have data in it yet, and it will be okay.
I have tried opening the file in Safe Mode, and I have installed all the latest Microsoft Office updates.
Has anyone else experienced an issue like this? Does it have something to do with the BeforeSave event macro?
UPDATE:
I changed the ActiveWorkbook to ThisWorkbook. Also, I have changed from editing the entire column to now finding the last used row and formatting that range excluding the header row.
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Application.EnableEvents = False
Cancel = True
Dim Lastrow As Integer
Lastrow = ThisWorkbook.Sheets("Pending").Cells(Rows.Count, 9).End(xlUp).Row
ThisWorkbook.Sheets("Pending").Range("I2:I" & Lastrow).NumberFormat = "#"
ThisWorkbook.Save
Application.EnableEvents = True
End Sub
Thank you.

As Zack & GWD advised in the comments, I updated the VBA to factor in the header row and set all references to ThisWorkbook instead of including ActiveWorkbook. So far the error has not occurred again. If it does happen in the future, I will post a new question if I cannot solve the issue.
Here is the updated code for reference:
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Application.EnableEvents = False
Cancel = True
Dim Lastrow As Integer
Lastrow = ThisWorkbook.Sheets("Pending").Cells(Rows.Count, 9).End(xlUp).Row
ThisWorkbook.Sheets("Pending").Range("I2:I" & Lastrow).NumberFormat = "#"
ThisWorkbook.Save
Application.EnableEvents = True
End Sub

Related

How to use excel after save event to run a power query query then save again

I have an excel Workbook that uses Power Query to populate a table. The query pulls information from multiple external Workbooks as well as a table in a Worksheet within the same Workbook.
The Worksheet in the same Workbook also stores changes to columns that are meant to be manipulated. The Worksheet in the same Workbook is part of a loop. It stores information that is pulled into the main table but also stores the changes made.
To make this work correctly, the Workbook needs to be Saved before the storage query runs. If a Save does not occur before running the query, the query will not contain the changes.
This is accomplished easily when clicking the save button. The following code works well:
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Application.EnableEvents = False
ThisWorkbook.Save
ThisWorkbook.Connections("Query - Stored").Refresh
Application.EnableEvents = True
End Sub
This does not work when the workbook is closed and save is clicked after clicking the document close.
The BeforeSave event does not fire because it does not get a chance to. The document closes and when it is reopened it shows it as a crashed file and is listed in the recovery list.
Can anyone help me understand why and how to overcome it.
Since this is caused by an Excel crash while closing, it's possible that the Refresh gets messed up when Close is underway.
You could try executing the Refresh before Closing, like this
Private Closing As Boolean
Private Sub Workbook_BeforeClose(Cancel As Boolean)
Closing = True
Application.EnableEvents = False
ThisWorkbook.Save
ThisWorkbook.Connections("Query - Stored").Refresh
Application.EnableEvents = True
End Sub
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
If Closing Then Exit Sub
Application.EnableEvents = False
ThisWorkbook.Save
ThisWorkbook.Connections("Query - Stored").Refresh
Application.EnableEvents = True
End Sub

Runtime error when using ActiveWorkbook.SaveCopyAs Filename

ActiveWorkbook.SaveCopyAs Filename: gives
Runtime error 1004
but hitting Debug>Run> Continue code runs as expected.
I have a macro enable Excel2016 spreadsheet. When updated and saved to PC I also wish to save a copy to my NAS. I have written code (see below) and used identical code, other than filename, for two other spreadsheets. These other two spreadsheets are saved as expected (i.e. to NAS and PC with no Runtime error))
Code as follows:
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
'Saves the current file to a backup folder and the default folder
'Note that any backup is overwritten
Application.DisplayAlerts = False
ActiveWorkbook.SaveCopyAs Filename:="\\ReadyNasDuo\Dell\Excelbak\finance18_19.xlsm"
ActiveWorkbook.Save
Application.DisplayAlerts = True
End Sub
I would expect problem file to act like the other two. Anyone any ideas why it does not. Only differences are that problem file is a lot larger, is password protected, has link to another spreadsheet and has far more 'coding'(i.e. more macros and VBA)
You must also deactivate the events Application.EnableEvents = False otherwise your Save/SaveCopyAs will trigger another Workbook_BeforeSave event.
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
'Saves the current file to a backup folder and the default folder
'Note that any backup is overwritten
Application.DisplayAlerts = False
Application.EnableEvents = False
ThisWorkbook.SaveCopyAs Filename:="\\ReadyNasDuo\Dell\Excelbak\finance18_19.xlsm"
'ActiveWorkbook.Save 'needed?
Application.EnableEvents = True
Application.DisplayAlerts = True
End Sub
Also I think you don't need ActiveWorkbook.Save because it will save at End Sub anyway as long as you don't set Cancel = True. The event is called BeforeSave not InsteadOfSave so the original save action will still happen when BeforeSave finished.
Note that ThisWorkbook and ActiveWorkbook are not the same. I assume that you meant to use ThisWorkbook which is the workbook this code is running in, while ActiveWorkbook is the one that has the focus (is on top) while the code is running.

Prevent Saving in excel couldn't be saved?

This may sound silly but I'm trying to prevent saving in Excel Workbook by using the code below in ThisWorkbook:
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Cancel = True
End Sub
Private Sub Workbook_BeforeClose(Cancel As Boolean)
Application.ThisWorkbook.Saved = True
End Sub
However, after pressing Ctrl + s, and close the workbook, when reopening it, the code wasn't saved.
Any idea why this happen ?
This is a good thing - it means your code is working right. Your code prevented you from saving the workbook yourself. I have this in a couple applications I have made, the way around it is to make a sub as follows:
sub saveTheWB()
Application.EnableEvents = False
ThisWorkbook.Save
Application.EnableEvents = True
end sub
You have to run this sub every time you want to save.
That's right because the Workbook_BeforeSave event handler is firing and cancelling the save operation.
In the Immediate window of The IDE, run Application.EnableEvents = False before saving your workbook and it will save with the code.
Don't forget to run Application.EnableEvents = True after!

Setting the "Title" property of an excel spreadsheet

First of all, I'm a total Excel interop noob.
I'm trying to get a date from a cell and then set the title of the document before the document gets saved, to be the month of the date. This is my code:
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
ThisWorkbook.Title = DateTime.Month(ThisWorkbook.Sheets("Sheet1").Cell("A10"))
End Sub
I'm not sure that anything is working. I set a breakpoint on the code, but I can't "run" it because it's not a macro, but an event handler, so I don't think the breakpoint is going to work. I don't get any errors. I don't even know that ThisWorkbook.Title is what I want and I'm not even sure about getting the month from the cell.
To change the 'Title' built in property in Excel:
ActiveWorkbook.BuiltinDocumentProperties("Title") = "My Title Name"
The title of the document is a "Built In" property - this is the info that appears when you right click on the file and look at the properties.
The name of the spreadsheet is set on save, so you will want to save the file with a new name if you want to see the date on the file itself
A code something like this should give you the result you desire:
(note that this code is VBA, so it may need some tweaking to work in interop.
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Dim FilePath As String
Dim varName As String
On Error GoTo ErrorHandler
' This disables all Excel events.
Application.EnableEvents = False
' disable the default behaviour of the save like so:
Cancel = True
'you can leave this blank if you want it to save in the default directory
FilePath = "C:\The path\To\The File"
varName = Format(ThisWorkbook.Sheets("Sheet1").Cell("A10"),"mmmm")
ActiveWorkbook.SaveAs Filename:=FilePath & varName & ".xlsx"
ErrorExit:
' This makes sure events get turned back on again no matter what.
Application.EnableEvents = True
Exit Sub
ErrorHandler:
MsgBox "No value submitted - File Not Saved"
Resume ErrorExit
End Sub
I assume this would serve your purpose:
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Application.Caption = MonthName(Month(ThisWorkbook.Sheets("Sheet1").Range("C10").Value))
End Sub
Another thing is:
This title would not be there next time you open the workbook. So:
Private Sub Workbook_Open()
Application.Caption = MonthName(Month(ThisWorkbook.Sheets("Sheet1").Range("C10").Value))
ThisWorkbook.Save
End Sub

Excel VBA - always show worksheet on open

How can the following conditions be met with VBA code?
A particular worksheet is always displayed on open, even if the worbook is opened without enabling macros.
A workbook user may save the workbook while working on any worksheet.
The save must not interfere with the user - no navigating away to a different sheet, no messageboxes, etc.
The regular save functions (Ctrl-S, clicking Save) must remain available and when used must obey the criteria above.
I'd like to avoid the attempted solutions I've listed at the bottom of this question.
Details:
The workbook is created using Office 2007 on a Windows 7 machine. It is an .xlsm workbook with 2 worksheets, "Scheduler" and "Info." Sheet tabs are not visible. Not all users will enabled macros when the workbook is opened.
Upon opening the workbook, a user will only be exposed to one sheet as follows:
"Info" shows up if macros are disabled, and basically tells anyone who opens the workbook that macros need to be enabled for full workbook functionality. If macros are enabled at this point, "Scheduler" is activated.
"Scheduler" is where data is stored and edited, and is automatically shown if macros are enabled. It is not presented to the user when the workbook is opened without macros enabled.
"Info" must show up first thing if the workbook is opened and macros are disabled.
Attempted Solutions (I'm looking for better solutions!):
Placing code in the Workbook.BeforeSave event. This saves with "Info" activated so it shows up when the workbook is opened. However, if the user is in "Scheduler" and not done, I cannot find a way in this event to re-activate "Scheduler" after the save.
Using Application.OnKey to remap the Ctrl-s and Ctrl-S keystrokes. Unfortunately this leaves out the user who saves using the mouse (clicking File...Save or Office Button...Save).
Checking during every action and if needed activating "Scheduler". In other words, inserting code in something like the Workbook.SheetActivate or .SheetChange events to put "Scheduler" back into focus after a save with "Info" activated. This runs VBA code constantly and strikes me as a good way to get the other code in the workbook into trouble.
Placing code in the Worksheet("Info").Activate event, to change focus back to "Scheduler". This leads to the result of "Scheduler", not "Info", showing when the workbook is opened, even with macros disabled.
Will this not work? Updated to handle Saving gracefully
Private Sub Workbook_Open()
ThisWorkbook.Worksheets("Scheduler").Activate
End Sub
Private Sub Workbook_BeforeClose(Cancel As Boolean)
ThisWorkbook.Worksheets("Info").Activate
If (ShouldSaveBeforeClose()) Then
Me.Save
Else
Me.Saved = True ' Prevents Excel Save prompt.
End If
End Sub
Private Function ShouldSaveBeforeClose() As Boolean
Dim workbookDirty As Boolean
workbookDirty = (Not Me.Saved)
If (Not workbookDirty) Then
ShouldSaveBeforeClose= False
Exit Function
End If
Dim response As Integer
response = MsgBox("Save changes to WorkBook?", vbYesNo, "Attention")
ShouldSaveBeforeClose= (response = VbMsgBoxResult.vbYes)
End Function
I don't have time to test this out, but you might be able to do this using Application.OnTime in your BeforeSave event handler. Something like:
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Dim objActiveSheet
Set objActiveSheet = Me.ActiveSheet
If objActiveSheet Is InfoSheet Then Exit Sub
If Module1.PreviousSheet Is Nothing Then
Set Module1.PreviousSheet = objActiveSheet
InfoSheet.Activate
Application.OnTime Now, "ActivatePreviousSheet"
End If
End Sub
Then in Module1:
Public PreviousSheet As Worksheet
Public Sub ActivatePreviousSheet()
If Not PreviousSheet Is Nothing Then
PreviousSheet.Activate
Set PreviousSheet = Nothing
End If
End Sub
Edit 2: Here is a re-write that does not utilize AfterSave. You may need to tweak the dialog created from GetSaveAsFilename according to your needs.
This relies on overriding default save behavior and handling the save yourself.
Private actSheet As Worksheet
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Cancel = True
PrepareForSave
manualSave SaveAsUI
AfterSave ThisWorkbook.Saved
End Sub
Private Sub PrepareForSave()
Set actSheet = ThisWorkbook.ActiveSheet
ThisWorkbook.Sheets("Info").Activate
hidesheets
End Sub
Private Sub manualSave(ByVal SaveAsUI As Boolean)
On Error GoTo SaveError 'To catch failed save as
Application.EnableEvents = False
If SaveAsUI Then
If Val(Application.Version) >= 12 Then
sPathname = Application.GetSaveAsFilename(FileFilter:="Excel Files (*.xlsm), *.xlsm")
If sPathname = False Then 'User hit Cancel
GoTo CleanUp
End If
ThisWorkbook.SaveAs Filename:=sPathname, FileFormat:=52
Else
sPathname = Application.GetSaveAsFilename(FileFilter:="Excel Files (*.xls), *.xls")
If sPathname = False Then
GoTo CleanUp
End If
ThisWorkbook.SaveAs Filename:=sPathname, FileFormat:=xlNormal
End If
Else
ThisWorkbook.Save
End If
SaveError:
If Err.Number = 1004 Then
'Cannot access save location
'User clicked no to overwrite
'Or hit cancel
End If
CleanUp:
Application.EnableEvents = True
End Sub
Private Sub AfterSave(ByVal bSaved As Boolean)
showsheets
If actSheet Is Nothing Then
ThisWorkbook.Sheets("Scheduler").Activate
Else
actSheet.Activate
Set actSheet = Nothing
End If
If bSaved Then
ThisWorkbook.Saved = True
End If
End Sub
Private Sub hidesheets()
For Each ws In ThisWorkbook.Worksheets
If ws.Name <> "Info" Then
ws.Visible = xlVeryHidden
End If
Next
End Sub
Private Sub showsheets()
For Each ws In ThisWorkbook.Worksheets
ws.Visible = True
Next
End Sub
Private Sub Workbook_Open()
AfterSave True
End Sub
The only way to make Info display first without macros enabled is if that is how the workbook was saved. This is most reasonably handled when saving.
Unless I misunderstood your issue, not using BeforeSave seems misguided. Just make sure to use AfterSave as well. Here's an example:
Private actSheet As Worksheet
Private Sub Workbook_AfterSave(ByVal Success As Boolean)
showsheets
actSheet.Activate
Set actSheet = Nothing
Thisworkbook.Saved = true 'To prevent save prompt from appearing
End Sub
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Set actSheet = ThisWorkbook.activeSheet
ThisWorkbook.Sheets("Info").Activate
hidesheets
End Sub
Private Sub Workbook_Open()
showsheets
ThisWorkbook.Sheets("Scheduler").Activate
End Sub
Private Sub hidesheets()
For Each ws In ThisWorkbook.Worksheets
If ws.Name <> "Info" Then
ws.Visible = xlVeryHidden
End If
Next
End Sub
Private Sub showsheets()
For Each ws In ThisWorkbook.Worksheets
ws.Visible = True
Next
End Sub
The use of the private object actSheet allows the "ActiveSheet" to be reselected after save.
Edit: I noticed you had more requirements in the comments. The code has been updated so that now upon saving, only the Info sheet will be visible, but when opened or after saving, every sheet will reappear.
This makes it so that any user opening the file without macros will not be able to save with a different sheet activated, or even view the other sheets. That would certainly help motivate them to enable macros!
This problem has been flogged to death in the past, its just hard to find a solution that actually works. Take a look at this code which should do what you need. Basically it shows a splash screen, with all other sheets hidden if the user does not enable macros. It will still save normally if the user clicks save and wont interfere with their work. If they save with there worksheet open it will still show only the splash screen when next opened. Download the sample file below and you can test for yourself, make sure you download the file posted by Reafidy it has over 400 views. If you need it modified further let me know.
Private Sub Workbook_BeforeClose(Cancel As Boolean)
bIsClosing = True
End Sub
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Dim wsArray() As Variant
Dim iCnt As Integer
Application.ScreenUpdating = 0
Splash.Visible = True
For Each wsSht In ThisWorkbook.Worksheets
If Not wsSht.CodeName = "Splash" Then
If wsSht.Visible = True Then
iCnt = iCnt + 1: Redim Preserve wsArray(1 To iCnt)
wsArray(iCnt) = wsSht.Name
End If
wsSht.Visible = xlSheetVeryHidden
End If
Next
Application.EnableEvents = 0
ThisWorkbook.Save
Application.EnableEvents = 1
If Not bIsClosing Then
For iCnt = 1 To UBound(wsArray)
Worksheets(wsArray(iCnt)).Visible = True
Next iCnt
Splash.Visible = False
Cancel = True
End If
Application.ScreenUpdating = 1
End Sub
Private Sub Workbook_Open()
Dim wsSht As Worksheet
For Each wsSht In ThisWorkbook.Worksheets
wsSht.Visible = xlSheetVisible
Next wsSht
Splash.Visible = xlSheetVeryHidden
bIsClosing = False
End Sub
A sample file can be found here.
How about using a 'proxy workbook'.
The 'proxy workbook'
is the only workbook which is directly opened by the users
contains the info sheet
contains VBA to open your 'real workbook' using Workbooks.Open (As I've checked with Workbooks.Open documentation by default it will not add the file name to your recent files history unless you set the AddToMru argument to true)
if required the VBA code could even make sure that your 'target workbook' is trusted (I found some sample code here)
The 'target workbook'
contains your Schedule and any other sheets
is only opened if the VBA code in 'proxy workbook' was executed
can be saved by the user at any time as usual
I've got no Office 2007 at hand to test this but think it should do.

Resources