I have an excel file that will be opened and accessed by hundreds of people, this file is only accessible through a database program so it is not on a network drive per se. The file has some simple code to hide the ribbon and formula bar, however if the file is opened and trust center settings are not set to accept internet files as safe the protected view mode steps in and asks for editing to be enabled. When enabled it then gives a run time error because it has not gone into normal view mode before the code executes. Link to MS article Object Model calls may fail from WorkbookOpen event when exiting Protected View this is a known issue. When I try and use the microsoft work around I can't get it to work. below is my code and the workaround code.
My code
Microsoft's work around
It should be noted that by no means am a expert at VBA I am more at a beginner level.
My code
Code:
Private Sub Workbook_Open()
With ActiveWindow
.DisplayHeadings = False
.DisplayHorizontalScrollBar = False
.DisplayVerticalScrollBar = False
.DisplayWorkbookTabs = False
End With
Application.Calculation = xlCalculationAutomatic
Application.CommandBars("worksheet menu bar").Enabled = False
Application.DisplayAlerts = False
Application.DisplayFormulaBar = False
Application.CommandBars("full screen").Visible = False
Application.CommandBars("formatting").Visible = False
Application.CommandBars("standard").Visible = False
Application.CommandBars("Control toolbox").Visible = False
Application.CommandBars("Forms").Visible = False
If Application.Version <= 11# Then
Application.DisplayFullScreen = False
ElseIf Application.Version > 11# Then
Application.ExecuteExcel4Macro "Show.ToolBar(""Ribbon"",False)"
Application.DisplayFormulaBar = False
End If
If Application.Version < "12.0" Then
MsgBox "You must use Excel version 2007 or later."
ActiveWorkbook.Close True
End If
Range("W9").Select
End Sub
Microsoft's work around
Code:
Option Explicit
Public WithEvents oApp As Excel.Application
Private bDeferredOpen As Boolean
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 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
It should be noted that by no means am a expert at VBA I am more at a beginner level.