Workbook_Open() does not work with Workbook Protection - excel

I am using Excel 2016 and have this code written in the ThisWorkbook object in VBA:
Private Sub Workbook_Open()
ThisWorkbook.Protect (password = "password")
End Sub
It is not working. The point here is that this should prevent users from touching the Power Query functions in this workbook. I have saved it as a Macro-enabled workbook, I have all macros and events enabled and this is the only workbook open.
I also have this additional code:
Private Sub Workbook_BeforeClose(Cancel As Boolean)
ThisWorkbook.Protect (password = "password")
ThisWorkbook.Save
End Sub
And that is not working either. It works fine if I insert that "ThisWorkbook.Protect" code into a general module or worksheet object and run it manually, but when I want this particular excel file to run this code automatically on open or close, it does not do it.
Any ideas what could be causing this?

For some reason running ThisWorkbook.Protect on a protected workbook seems to unprotect it (even though I couldn't find any documentation that says that it does this) so try this:
Private Sub Workbook_BeforeClose(Cancel As Boolean)
If Not ThisWorkbook.ProtectStructure Then ThisWorkbook.Protect Password:="password"
ThisWorkbook.Save
End Sub

In order for automatically-running subroutines to work correctly in Microsoft Excel, they must be contained within a Visual Basic module.
If an Auto_Open, Auto_Close, or other automatically-running subroutine is stored "behind" a worksheet or ThisWorkbook, it may not function correctly when you open or close your workbook, or when you perform an action that should cause the subroutine to run.
MS Topic Discussion - Code "Behind" a Workbook

Related

Automatically Run VBA Code when an Excel Workbook Opens

I have VBA code in I would like to run when the Excel workbook is opened.
I tried creating a public procedure in the sheet the code is supposed to run in:
Public Sub Workbook_Open
' Some code here
End Sub
It does not run when the workbook opens.
It is supposed to create a combobox in one of the cells and then fill it with information from the database.
Make sure that the code is in the ThisWorkbook scope of the VBA editor and not in a module or worksheet:
Option Explicit
Private Sub Workbook_Open()
MsgBox "Autorun works!"
'your code here
End Sub
And make sure that your macros are enabled.
For details also see Microsoft's documentation: Automatically run a macro when opening a workbook.
Adding to #Pᴇʜ's answer, you can also use the following procedure in standard module:
Sub Auto_Open()
'// Your code here...
End Sub
You are trying to create an event procedure that activates when you open a book. Go to thisworkbook in the VBA editor and choose workbook open procedure from the drop down list above the coding window, or you can type manually:
Private Sub Workbook_Open()
End Sub

Excel vba - How to refer to workbook builtin document properties in excel VBA?

I am building a macro workbook in which ctl+D is deactivated.
Now, the issue is - When another workbook is opened when this macro workbook is still open, ctl+D is getting disabled in the other workbook as well, as this is an application level setting. I want to restrict disabling ctl+D only in the macro workbook.
For this, I can add a condition in the code which checks for the workbook name before disabling ctl+D. But, there is 90% chance that users would change the name of the workbook after saving to their desktop.
Is there a way I can use Workbook builtin properties instead of workbook name in code? Please advise.
Thank you!
https://msdn.microsoft.com/en-us/library/microsoft.office.tools.excel.workbook.builtindocumentproperties.aspx?cs-save-lang=1&cs-lang=vb#code-snippet-1
Example (Pseudo code):
if ThisWorkbook.Title = 'TEST' Then
Application.OnKey "^d", ""
end if
Use workbook events to detect when the workbook is activated or not.
Private Sub Workbook_Activate()
Application.OnKey "^d", ""
End Sub
Private Sub Workbook_Deactivate()
Application.OnKey "^d"
End Sub
Put this in the ThisWorkbook module. You might also want to add the Ctrl+d deactivation line to a Workbook_Open event.

Excel's VBA ActiveWorkbook is "Nothing" when "Enable Editing" from ProtectedView

I have a VBA macro which is called from a spreadsheet function (user defined function, UDF). When the spreadsheet is downloaded from the internet and the user has set "Trust Center" settings accordingly, the spreadsheet will open in so the called "Protected View". The function will not be called. A button "Enable Editing" is shown.
If the button is pressed, the spreadsheet is "trusted" and reopened normally, starting calculation, and hence calling the user defined function.
However, in that VBA function the value of Application.ActiveWorkbook is Nothing. This can be verified in the debugger.
Since I just need to read some properties (like path name) of the spreadsheet, I could alternatively inspect the availability of Application.ActiveProtectedViewWindow which should reference to the protected version of the workbook. In the debugger, this object can be inspected. However, running in release (without debug) the value of Application.ActiveProtectedViewWindow is also Nothing.
Both behaviors - especially the first one - appears to be a bug present in Excel 2010 and 2013 (see also a post at the MSDN forum ).
Question: Is there a way to get hold of properties of the active workbook after it has been enabled for editing?
PS: As a follow up to the nice observation of Siddharth Rout, that "ThisWorkbook" might work: In my case, the macro is not part of the Workbook being openend. The UDF is defined in an XLA. Hence, ThisWorkbook would reference the XLA. I do need to get the ActiveWorkbook (= the workbook calling the UDF) instead of ThisWorkbook (= the workbook running the UDF).
IMPORTANT REQUIREMENT:
My function is called as a user defined function, i.e., execution order is determined by Excel updating the cell.
The function is not part of the workbook being opened. It is part of an XLA.
I cannot add any code to the workbook which is opened.
Summary: The problem can be replicated and there are some possible workarounds. The most promising one - resulting from a chat - is to use ActiveWindow.Parent instead of ActiveWorkbook.
I was able to replicate the problem.
I tried
Private Sub Workbook_Open()
MsgBox "Application.ActiveWorkbook Is Nothing = " & _
CStr(Application.ActiveWorkbook Is Nothing)
End Sub
And I got True
However, then I tried this and it gave me False
Private Sub Workbook_Open()
MsgBox "Application.ActiveWorkbook Is Nothing = " & _
CStr(Application.ThisWorkbook Is Nothing)
End Sub
Now answering your question...
Question: Is there a way to get hold of properties of the workbook after it has been enabled for editing?
Yes. Use ThisWorkbook instead of ActiveWorkbook
Followup From Comments
Once the workbook completely loads after you exit the Protected Mode, you would be able to access the ActiveWorkbook object. To test this, put this code in the protected file.
Private Sub Workbook_Activate()
MsgBox "Application.ActiveWorkbook Is Nothing = " & _
CStr(Application.ActiveWorkbook Is Nothing)
End Sub
You will notice that you get a False
So once your workbook loads, your add-in can use ActiveWorkbook to interact with the opened file.
Here is another test
Private Sub Workbook_Activate()
MsgBox ActiveWorkbook.Path
End Sub
This is what I got the moment, I exit the Protected Mode
FOLLOWUP FROM CHAT
Using ActiveWindow.Parent.Path instead of ActiveWorkbook.Path would solve the problem.
I had this same issue today, and neither the accepted answer nor any other answer that I could find on this page or through searching the Google-verse worked for me. I'm using the version of Excel within Office 365, and I figured that was at the root of the problem.
I eventually came to a solution after finding a Microsoft Excel 2010 resource and hitting the old try-fail cycle for a few hours. Here's what I got:
Option Explicit
Public WithEvents oApp As Application
Private bDeferredOpen As Boolean
Private Sub Workbook_Open()
Set oApp = Application
End Sub
Private Sub oApp_WorkbookActivate(ByVal Wb As Workbook)
If bDeferredOpen Then
bDeferredOpen = False
Call WorkbookOpenHandler(Wb)
End If
End Sub
Private Sub oApp_WorkbookOpen(ByVal Wb As Workbook)
Dim oProtectedViewWindow As ProtectedViewWindow
On Error Resume Next
'The below line will throw an error (Subscript out of range) if the workbook is not opened in protected view.
Set oProtectedViewWindow = oApp.ProtectedViewWindows.Item(Wb.Name)
On Error GoTo 0
'Reset error handling
If oProtectedViewWindow Is Nothing Then
bDeferredOpen = False
Call WorkbookOpenHandler(Wb)
Else
'Delay open actions till the workbook gets activated.
bDeferredOpen = True
End If
End Sub
Private Sub WorkbookOpenHandler(ByVal Wb As Workbook)
'The actual workbook open event handler code goes here...
End Sub
The difference between the 2010 solution and mine is that I had to call Workbook_Open and explicitly set the oApp variable there, because without that assignment neither the oApp_WorkbookActivate nor oApp_WorkbookOpen functions would fire when I opened the file.
Figured that someone else might be able to benefit from this, so I posted it, despite the fact that the most recent update to this thread is better than 2 years old.
Best.
Try using Application.Caller.Parent.Parent instead of Application.Activeworkbook
This is not a complete answer to the original question, but a (dirty) workaround for a problem related to this.
I needed ActiveWorkbook to infer the workbooks path, that is ActiveWorkbook.Path.
An alternative to using ActiveWorkbook.Path is to check for Application.RecentFiles(1).Path which is the path of the most recently opened file. In many cases this will be the workbook for which the user just has "Enabled Editing". However, of course, this method may fail: In the case the used opened another sheet, then enabling the previously opened sheet.
(Note: ActiveWorkbook.Path give the path of the folder, while Application.RecentFiles(1).Path gives the complete path of the file, so there has to be some post-processing).
I know it's old thread, but i came across the same issue and i found solution ;)
The only way to go around it, is to use variable type Workbook
Dim wbk as Workbook
Set wbk = Application.ProtectedViewWindows(index).Workbook
Warning:
ActiveSheet returns Nothing when active window is protected too.
Dim wsh As Worksheet
Set wsh = wbk.Worksheets(index)
Try this code it works.
If (UCase(ActiveWorkbook.Name) = ucase("<YOUR XLA NAME WITH EXTENSION>")) Then
End
End If
Set wbObj = ActiveWorkbook
First time when you run the macro, it just ends without doing anything. Second time it picks up the proper file.

Saving Personal.xls automatically

I use Excel 2003 on a Windows 7 Professional setup.
In my Personal.xls file, I have compiled snippets of code/formulae that I have picked up from different places, to be available for ready reference when I use Excel. These contain a number of volatile functions such as cell(), rand(), today() etc. As a result, when I close Excel, it asks me whether I would like to save Personal.xls.
I would like to keep my Personal.xls as it is, and yet disable the popup somehow. I am fine with saving, not saving, either way, as I won't be changing Personal.xls.
I have tried the following code in my personal.xls in the Workbook_BeforeClose section
Private Sub Workbook_BeforeClose(Cancel As Boolean)
ThisWorkbook.Save
End Sub
But it doesn't seem to work. I have tried some variations, including .Save and .Saved=True, and also tried to alternatively use ThisWorkbook., Me. & Workbooks("PERSONAL.xls"). However, Excel still asks me save Personal.xls
I have also tried to disable calculations in my Personal.xls viz.
Private Sub Workbook_Open()
For Each ws In ThisWorkbook.Worksheets
ws.EnableCalculation = False
Next
End Sub
This doesn't solve the problem either. Finally I tried to do a 'ThisWorkbook.Save' after changing calculation mode to manual, but that doesn't change anything either.
Am I missing something here? Any advice would be appreciated. Thanks in advance!
You want:
Me.Save
In your workbook BeforeClose event.
Why not just force-shut the document?
Private Sub Workbook_BeforeClose(Cancel As Boolean)
ThisWorkbook.Close savechanges:=True
End Sub
For what I was trying to do I am actually using savechanges:=False. Both ways worked.
I just remove the Cancel As Boolean
Private Sub Workbook_BeforeClose()
ThisWorkbook.Save
End Sub

how to load sapbex.xla when the workbook opens

I open a query from SAP BW... I make all the changes I need and I even check the box that says Refresh query every time you open the workbook. The problem is that when I reopen the workbook it's just like a regular Excel, because the SAPBEX.xla file is not loaded anymore.
Any ideas on how can I solve this?
I want the workbook updated with the latest data every time I open the workbook.
Thanks!
You can use an application event (see Chip Pearson's website).
Put this code in the This Workbook module of your PERSONAL.XLSM (see here).
Private WithEvents App As Application
Private Sub Workbook_Open()
Set App = Application
End Sub
And in a module:
Private Sub App_WorkbookOpen(ByVal Wb As Workbook)
MsgBox "New Workbook: " & Wb.Name
'or better check here if this is your workbook and activate the addin
End Sub

Resources