Excel VBA - always show worksheet on open - excel

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.

Related

Workbook_BeforeClose - Standard saving form pops out but error 91 when clicking on "Cancel"

I would like to write a code which, before closing the Workbook, sets all the sheets except one cover as very hidden.
I click on the "X" to close the Workbook, the Macro is fired and everything fine.
Then I receive the classic saving form of Excel and, if I click cancel, I receive error 91 - Object variable or With block variable not set.
Could someone explain me why is happening? I used the same code in the past and I did not have this issue
It is interesting because, if there is another excel workbook open at the same time, it works everything fine.
In Tab ThisWorkbook:
Private Sub Workbook_BeforeClose(Cancel As Boolean)
Application.EnableEvents = True
Call my_macro 'defined in a separate module
Application.EnableEvents = False
End Sub
For the sake of clarity in Module 1 the code is following:
Public Sub my_macro()
Application.ScreenUpdating = False
On Error GoTo skip
Dim ws As Worksheet
Sheet8.Visible = True
For Each ws In Worksheets
If ws.Name = "Cover" Then
Else
ws.Visible = xlSheetVeryHidden
End If
Next ws
Sheet8.Select
Range("A1").Select
Application.ScreenUpdating = True
ActiveSheet.EnableSelection = xlNoRestrictions
Application.EnableEvents = True
skip:
Application.EnableEvents = True
End Sub

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

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 do I allow only myself to view a spreadsheet but everyone else can only a userform?

Trying to work out how only I can see the work book and everyone else can see the userform, based on network username.
Here's what I've got so far:
Private Sub Workbook_Open()
Application.Visible = False
UtilitiesReportingTool.Show
End Sub
You'll need a couple of things to stop your users looking at your worksheets - and these can easily be broken with a little knowledge.
Create a sheet with big text saying "Please enable macros"
Very hide all sheets except the macro enable sheet.
Create these two procedures in a normal module
Sub StartUp()
Dim wrkSht As Worksheet
If Environ("username") <> "CAES_MATT" Then
Application.Visible = False
UtitlitiesReportingTool.Show
Else
For Each wrkSht In ThisWorkbook.Worksheets
wrkSht.Visible = xlSheetVisible
Next wrkSht
End If
End Sub
Sub ShutDown()
Dim wrkSht As Worksheet
For Each wrkSht In ThisWorkbook.Worksheets
Select Case wrkSht.CodeName
Case "Sheet1" 'This should really be shtMacroEnable or something.
wrkSht.Visible = xlSheetVisible
Case Else
wrkSht.Visible = xlSheetVeryHidden
End Select
Next wrkSht
End Sub
In your Workbook_Open event add this code:
Private Sub Workbook_Open()
StartUp
End Sub
In your UserForm_Terminate event add this:
Private Sub UserForm_Terminate()
Application.Visible = True
ShutDown
End Sub
When you open the workbook only the 'Enable Macros' sheet will be visible if macros aren't enabled.
When macros are enabled the form is displayed, unless it's you in which case all the sheets are unhidden.
When the form is closed everything except the sheet with codename Sheet1 is hidden.
I may have missed something ... heading home.

Automatically save the last open Excel file date

Currently I have a code that allows me to produce the current date when I run the code. However, I would like date automatically to be updated when it is closed so then when I open it the next time, I would know when was the date last opened. Below is the code that I have currently:
Private Sub Worksheet_Activate()
Dim Home As Worksheet
Set Home = Worksheets("Program Status Summary")
Home.Range("A1").Value = Format(Now(), "dd/mmm/yyyy")
End Sub
To follow up on my comment: Simply add an event handler for Workbook_BeforeClose to the workbook object of the VBA project.
Private Sub Workbook_BeforeClose(Cancel As Boolean)
Dim Home As Worksheet
Set Home = Worksheets("Program Status Summary")
Home.Range("A1").Value = Format(Now(), "dd/mmm/yyyy")
End Sub
You'll probably want to save the changes as well in order to prevent a "save changes" prompt.
Update: The following example automatically saves changes if the workbook was saved before the code made changes. This is necessary to avoid saving changes that the user didn't intend.
Private Sub Workbook_BeforeClose(Cancel As Boolean)
Dim wasSaved As Boolean
wasSaved = ThisWorkbook.saved
Dim Home As Worksheet
Set Home = Worksheets("Program Status Summary")
Home.Range("A1").Value = Format(Now(), "dd/mmm/yyyy")
If wasSaved Then ThisWorkbook.Save
End Sub
Private Sub Workbook_BeforeClose(Cancel As Boolean)
Range("A1") = Date
ThisWorkbook.Save
End Sub
This would do it.
The "ThisWorkbook.save" part saves the workbook after adding with the current date

Error on Userform.Hide inside Workbook_Deactivate event

As the title say I've been having one particular problem with my userform. When I close it (with a command button) an error pops on Userform.Hide inside the Workbook_Deactivate event.
This is the code on the Userform_initialize event:
All variables in here are global
VBA:
Private Sub Userform_Initialize()
subRemoveCloseButton Me
Set pagina = ThisWorkbook.Worksheets("Ruta")
Set libro = Workbooks.Open(pagina.Range("B4").Value, False, True)
Set pagina2 = libro.Worksheets("GLOBAL")
pasadas = 0
If pagina2.AutoFilterMode Then
If pagina2.FilterMode Then
pagina2.ShowAllData
End If
ElseIf pagina2.FilterMode Then
pagina2.ShowAllData
End If
pagina2.Columns("A:IV").EntireColumn.Hidden = False
lastRow = pagina2.Cells(pagina2.Rows.Count, "B").End(xlUp).Row
Call RemoveDuplicates
With Me.ImagenDatos
.ScrollBars = fmScrollBarsBoth
'Change 8.5 to suit your needs
.ScrollHeight = .InsideHeight * 5
.ScrollWidth = .InsideWidth * 3
End With
End Sub
Then in the CommandButton_Click event I have this:
VBA:
Private Sub BotonCerrar_Click()
Unload Consultas
libro.Saved = True
libro.Close
ThisWorkbook.Close
End Sub
The error, as already commented, comes from this:
VBA:
Private Sub Workbook_Deactivate()
Consultas.Hide
End Sub
If I comment that single line the Userform closes with no problem but I need it so the userform (Consultas) hides when the user switches between workbooks.
The error message says: Object variable or With block variable not set (Error 91)
Anyone have a clue on what's going wrong?
This is my first post and if something else is needed just let me know.
I would appreciate any help on this.
EDIT: I have more code but I think this is pretty much the essential as all I do is open the excel workbook, then the userform shows and then I click the button that closes the userform
So this is how I solved this:
Before trying to hide the userform Consultas on the Workbook_Deactivate event I first checked if the userform was visible with the link provided by #Ralph.
That solved part of the problem but then the error moved to the part where I close libro :
Private Sub BotonCerrar_Click()
Unload Consultas
libro.Saved = True
libro.Close
ThisWorkbook.Close
End Sub
The error persisted even before unloading the userform as suggested by #A.S.H but I fixed it calling Application.Workbooks(libro.Name).Close False instead of libro.close False (If someone could explain this to me I would really appreciated it)
The final code is the following:
Private Sub BotonCerrar_Click()
Dim wb As Workbook
Dim otrolibro As Boolean
otrolibro = False
Application.Workbooks(libro.Name).Close False
Unload Consultas
For Each wb In Workbooks
If wb.Name <> ThisWorkbook.Name Then
otrolibro = True
Exit For
End If
Next wb
If otrolibro = True Then
ThisWorkbook.Close False
Else
ThisWorkbook.Saved = True
Application.Quit
End If
End Sub
The For cicle is to quit the excel application if there is not another Workbook open because if I just close all Workbooks, an Excel window remains open with nothing on it.

Resources