I have the following code:
Private Sub CommandButton3_Click()
Dim SPATH As String
Dim myFileName As Variant
If MsgBox("Some Question...", vbYesNo) = vbNo Then Exit Sub
'Used to open the VO2 report taken from the Metabolic Cart. Will close later
myFileName = Application.GetOpenFilename(FileFilter:="Excel Files,*.xls*")
If myFileName <> False Then
Application.ScreenUpdating = True
Workbooks.Open Filename:=myFileName
End If
MultiPage2.Value = 3
End Sub
It's job is to search for and open another Excel file while a userform is being run with the workbook it's currently tied to is visible=False with this:
Private Sub Workbook_Open()
Application.ScreenUpdating = False
ThisWorkbook.Application.Visible = False
UserForm2.Show
Windows(ThisWorkbook.Name).Visible = True
Application.Visible = True
Application.ScreenUpdating = True
End Sub
Also important note: Showmodal for this userform is True
When this is run using Excel 2016, it works no problem (i.e. I am able to use a refedit on the userform while the loaded Excel file is visible to use it on).
On my work computer which has an older version of Excel, the loaded Excel file is invisible (meaning I can't use the refedit I have on the userform).
Does anyone know what may be going on or have a possible solution?
Related
I have made a .xlam file that holds some macro's. I use these macro's as a button in my ribbon.
Most of these macro's are opening other Excel sheets. But whenever I use that macro's the ribbon is blocking, I can not use any of the tabs or the buttons in those tabs.
Does anyone know why this happens? This is an example of the code that I added as a macro in the ribbon.
Sub OpenBureauplanning()
Application.ScreenUpdating = False
Dim Path As String
Path = "J:\Planning\Bureauplanning\"
Dim openfile As String
openfile = Path & "Bureauplanning.xlsm"
Workbooks.Open (openfile)
Application.ScreenUpdating = True
End Sub
After the replies from Dai. I removed the part "application.screenupdating" then its working fine.
In a different code, I use a form to determine which file needs to be opened. I also use that code in my ribbon.
That code is this:
Sub OpenProjectplanning()
Open_projectplanning.Show
End Sub
When running this code these forms get opened. In this form, people fill in the project number from the file that needs to be opened.
When the button "openen" is pressed the following code is starting:
Private Sub CommandButton1_Click()
Dim Path As String
Path = "J:\Planning\Projecten\"
Dim File As String
File = TextBox1.Text
Dim openfile As String
openfile = Path & File & ".xlsm"
Workbooks.Open (openfile)
Unload Me
End Sub
When opening the project file this code is automatically running on open:
Private Sub Workbook_Open()
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
Application.EnableEvents = True
Application.DisplayStatusBar = True
ThisWorkbook.Worksheets("Planning").Activate
End Sub
After running these codes, the ribbon is blocked.
Whenever the code is executed while multiple workbooks are open, office stops working with a message
Microsoft Office Excel has stopped working
Windows can try to recover your information and restart the program.
What's wrong with the code? I'm using MS Office 2007 on Windows7
Private Sub Workbook_BeforeClose(Cancel As Boolean)
close_without_saving
End Sub
Sub close_without_saving()
Application.DisplayAlerts = False
ThisWorkbook.Saved = True
If Application.Workbooks.Count < 2 Then
Application.Quit
Else
ThisWorkbook.Close
End If
End Sub
If you want to close the workbook without incorporating changes. Then you can use code like this in workbook module ~
Sub Auto_Close()
ThisWorkbook.Saved = True
End Sub
You can also use this for closing workbook without saving changes.
Sub CloseBook2()
ActiveWorkbook.Close savechanges:=False
End Sub
This routine can be attached to Close X Button. Workbook never closes partially, it will always close with all sheets contained in this workbook. DisplayAlerts = False and subsequently True can be incorporated in the routine. That should not create a problem like
Sub CloseBook()
Application.DisplayAlerts = False
ActiveWorkbook.Close
Application.DisplayAlerts = True
End Sub
Hi I am working on a project where I have to let users open excel while the Userform is opened.I can navigate through other excel files but not the one from Explorer.Please help.It would be of great help for me.
Option Explicit
Private Sub Workbook_Open()
Application.OnTime Now, "ThisWorkbook.OnlyOneOfMe"
Dim wks As Worksheet
For Each wks In ActiveWorkbook.Worksheets
wks.Protect Password:="Nothing", _
UserInterfaceOnly:=True
Next wks
End Sub
Private Sub Workbook_BeforeClose(Cancel As Boolean)
'important to reset this
Application.IgnoreRemoteRequests = False
End Sub
Private Sub OnlyOneOfMe()
Dim XlApp As Excel.Application
On Error Goto BAD
With Application
If Me.ReadOnly Or .Workbooks.Count > 1 Then
Me.ChangeFileAccess Mode:=xlReadOnly
Set XlApp = New Excel.Application
XlApp.Visible = True
XlApp.Workbooks.Open (Me.FullName)
Goto BAD
Else
'stop opening from explorer (but not from excel)
.Visible = False
.IgnoreRemoteRequests = True
UserForm1.Show
.Visible = True
.Quit
End If
Exit Sub
End With
BAD: If Err Then MsgBox Err.Description, vbCritical, "ERROR"
Set XlApp = Nothing
Me.Close False
End Sub
If the UserForm is modal it will lock the instance of excel until the form is closed.
You need to make the UserForm non Modal or close it after the workbook is opened.
Or you may Disable events before opening the workbook, that will prevent the UserForm to popup.
Just put this before the line where you open the workbook
Application.EnableEvents = False
And after the opening line enable the evens again
Application.EnableEvents = True
And you need to Enable/Disable the events for correct instance/application since you are opening new.
like this:
XlApp.EnableEvents = False
XlApp.Workbooks.Open (Me.FullName)
XlApp.EnableEvents = True
But you probably wont need to open new excel instance if this would work.
Also put the events enabling line to the ErrorHandling
If Err Then Application.EnableEvents = True: MsgBox Err.Description, vbCritical, "ERROR"
You can also try to hide all opened UserForms.
Put this right after you open the workbook:
For Each Object In VBA.UserForms
Object.Hide
Next
I would rather use a visual basic script to open up the userform in your VBA project. Put the following code on a plain text file and save it with the '.vbs' extension.(This must be in the same folder as the excel file containing the userform)
Option Explicit
Dim fso, curDir
Dim xlObj, file
Dim fullPath
Const xlMaximized = -4137 'constant to maximizes the background excel window
On Error Resume next
Set fso = CreateObject("Scripting.FileSystemObject")
curDir = fso.GetAbsolutePathName(".")
file ="\~$YourExcelFileName.xlsm"
fullPath = curdir & File
If fso.FileExists(fullPath) Then ' checks if the project is open or not
MsgBox "The project is in use!",64, "Notificación"
Else
file ="\YourExcelFileName.xlsm"
fullPath = curdir & file
Set fso = Nothing
Set xlObj = CreateObject("Excel.Application")
With xlObj
.WindowState = xlMaximized
.Visible = False
.Workbooks.Open fullPath
.IgnoreRemoteRequests = True
.Run "mainMethod"
End With
set xlObj=Nothing
End If
... then add a public subroutine in your vba project to listen the call from the previous VBScript (name the subroutine as above, I've called mainMethod)
Public Sub mainMethod()
UserForm1.Show vbModeless
End Sub
... you also have to attach an userform_terminate event to indicate that when you close the userform it must quit the current and active instance of excel:
Private Sub UserForm_Terminate()
Application.Quit
End Sub
... and of course you have to write a workbook's before_close event to reset the .IgnoreRemoteRequests to false, as follow (You can also write this in the previous userform_terminate event handler, but I believe this a tidier way to do it):
Private Sub Workbook_BeforeClose(Cancel As Boolean)
ThisWorkbook.Saved = True 'if needed
Application.IgnoreRemoteRequests = False
End Sub
Once you manage to do that, you'll have a very clean stand alone application, no one will notice it comes from an excel file and it won't interfeers with any other excel instance. Good Luck.
Andrés Alejandro García Hurtado
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 have 3 input boxes that when a document is selected it opens the document and fills in a select box. With Excel 2013 these windows are opened in front of the document and have to be minimized in order to select the next one. Is there a way to have it automatically open documents in the background?
Workbooks.Open (file_path)
If Application.Version >= 15# Then
ActiveWindow.WindowState = xlMinimized
End If
This what I currently have, however I would rather it open in the background in the first place over having to minimize it. I have tried to turn off screen updating for the part, however that did not work.
Application.ScreenUpdating = False
Workbooks.Open (file_path)
Application.ScreenUpdating = True
Does Application.ScreenUpdating affect WorkBooks.open in Excel 2013?
Application.ScreenUpdating will not work with excel 2013.
You may try creating function:
Sub myScreenUpdate(screenUpdateRequest As Boolean, previousScreenUpdate As Boolean)
If screenUpdateRequest Then
Application.ScreenUpdating = previousScreenUpdate
Else
previousScreenUpdate = Application.ScreenUpdating
Application.ScreenUpdating = False
End If
End Sub
call req:
Call myScreenUpdate(False, previousScreenUpdate)
Call myScreenUpdate(True, previousScreenUpdate)
Dim previousScreenUpdate as boolean
Call myScreenUpdate(False, previousScreenUpdate) 'to get the current setting into previousScreenUpdate
Call myScreenUpdate(True, false) 'to set updating to false
'do your heavy code here and when finished:
Call myScreenUpdate(True, previousScreenUpdate)