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
Related
I have macro that lets the user know how much time has past since the they last saved the workbook (it helps them know when they should save again), and it work great. Now I want to do this:
When the user saves the file, I want to note this to the user, by changing a cell value to 'Saving..." (while the saving process is being done), and when saving is finished - change that value to 'Saved'. (it takes a few seconds to save the file)
I tried this:
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Sheet4.Range("b3").Value = "Saving..."
End Sub
Private Sub Workbook_AfterSave(ByVal Success As Boolean)
Sheet4.Range("b3").Value = "Saved"
End Sub
It actually works OK expected for one little thing:
When the AfterSave fires, it changes the cell value - after file was saved, and that means that the user would need to save again if they attempt to close the file right after they had just saved.
I then tried this, to prevent the seemingly redundant second-time saving:
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Sheet4.Range("b3").Value = "Saving..."
Application.ScreenUpdating = False
Sheet4.Range("b3").Value = "Saved"
End Sub
Private Sub Workbook_AfterSave(ByVal Success As Boolean)
Application.ScreenUpdating = True
End Sub
I thought that if I set ScreenUpdating=False and do the cell change (before saving), it would work, but for some reason it doesn't work. The cell's value is changed to 'Saved' before the saving executes (while ScreenUpdating=False).
Any idea how to get it to work?
Keep your first attempt and Add this to the bottom of the second one:
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Sheet4.Range("b3").Value = "Saving..."
End Sub
Private Sub Workbook_AfterSave(ByVal Success As Boolean)
Sheet4.Range("b3").Value = "Saved"
ThisWorkbook.Saved = True
End Sub
This may work, it tricks the workbook to think that is has been saved and will let you close it without needing to save the second time after B3 was changed to Saved. However the next time you open the Workbook it will say "Saving..." on B3 instead of "Saved", you can clear B3 on Workbook_Open() and that should work.
I have a command button to save an Excel workbook in a particular format.
I want that the users are unable to save the workbook unless they click that command button.
To prevent the use of traditional saving options I used the code below:
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
MsgBox "You can't save this workbook!"
Cancel = True
End Sub
How do I prevent traditional saving options but allow saving if the command button is clicked?
You can have a boolean flag to indicate whether or not saving is allowed and only set it to true when you call the macro that contains your logic for saving the workbook.
Add the following code under ThisWorkbook:
Public AllowSave As Boolean
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
If Not AllowSave Then
MsgBox "You can't save this workbook!"
Cancel = True
End If
End Sub
Public Sub CustomSave()
ThisWorkbook.AllowSave = True
' TODO: Add the custom save logic
ThisWorkbook.SaveAs '....
MsgBox "The workbook has been saved successfully.", , "Workbook saved"
ThisWorkbook.AllowSave = False
End Sub
Note that you'll need to assign the CustomSave macro to the button that will be initiating the custom save.
Demo:
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
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.
I am trying to prevent an excel workbook from closing based-on the state of a checkbox.
My sample code that is placed in 'ThisWorkbook' :
Private Sub Workbook_BeforeClose(Cancel As Boolean)
If CheckBox0.Value = "FALSE" Then
b = MsgBox("Are you sure that you want to submit?", vbYesNo)
End If
If b = vbNo Then Cancel = True
End Sub
At the moment, I am getting a run-time error 424 , object required and the debug points at the If CheckBox0.Value..... line.
I am not sure what I am doing wrong and I'm not a regular VBA user.
Help, please.
I think you're using an embedded Checkbox (ActiveX). If so, you need to specify the sheet that the checkbox lives in. You can't just say Checkbox0 because you can have Checkbox0 on multiple sheets.
The other thing is that you can't check for "False" because it's not a string, but a boolean value, so you can just use False because that is an inherent VBA keyword.
Here's what I think you're looking for:
Private Sub Workbook_BeforeClose(Cancel As Boolean)
Dim b As Long
If (Sheets("Sheet1").CheckBox1.Value = False) Then
b = MsgBox("Are you sure that you want to submit?", vbYesNo)
End If
If b = vbNo Then Cancel = True
End Sub
EDIT:
Forgot to mention to switch "Sheet1" for the sheet name that your checkbox lives in.