首页 > 解决方案 > 退出受保护视图时,对象模型调用可能会因 WorkbookOpen 事件而失败

问题描述

在我的 workbook_open 事件中,我有一些代码会提示运行时错误 1004(见图)。

在此处输入图像描述

我认为是我的问题。但我找不到任何好的解决方案,我无法使用链接中的代码(或让它工作)。我做了一些研究,但之前的问题都没有包含任何好的答案。

快速了解问题:离开“受保护的视图”(通过按“启用编辑”)时,会触发 workbook_open,但实际上并未打开文件,因此代码“worksheets("...") 返回 null 并且显示错误。

这是我的代码示例:

Global CombinationRange As Range
Global FirstTimeOpen As Range
Global FirstTimeOpenToday As Range
Global BuildNumber As Range

Private Sub Workbook_Open()

    Call LoadVariables
    
    Dim ws As Worksheet
    For Each ws In ThisWorkbook.Worksheets
        If ws.Name = "LoginPage" Then
        Else
        ws.Visible = False
        End If
    Next
    
    'Depending on the file was newly created or not, open applicable LoginForm
    If FirstTimeOpen = "No" Then
        Startpage.show
        Else
        Loginform.show
    End If
    
End Sub

Sub LoadVariables()

'General
'======================================================================================================================================================
    Set CombinationRange = Worksheets("Master").Range("GZ8:GZ20") ' Range whereas all correct login are to activate users.
    Set FirstTimeOpen = Worksheets("Basic Data").Range("S4") ' Displays "Yes" or "No" depending on if this is the first time the files is opened
    Set FirstTimeOpenToday = Worksheets("Basic Data").Range("S7") ' Displays "Yes" or "No" depending on if this is the first time the files is opened today.
    Set BuildNumber = Worksheets("Basic Data").Range("N193")
'======================================================================================================================================================

End Sub

请注意,此工作簿将由许多不同的人打开,因此在信任中心更改我的设置不是解决方案。

任何想法如何避免这个错误?

标签: excelvba

解决方案


注意:这不是答案。只是我使用的一种解决方法。

由于这个问题,我不得不在启动文件时找到另一种方法来运行我的代码。我通过编写在保存文件时运行的代码解决了这个问题,这意味着我没有“保护视图”的问题。我正在“强制”文件进入“注销”模式,而所有工作表都被隐藏和保护(所有列也被隐藏),但“登录页面”除外。当您打开文件时,系统会提示您单击一个按钮,然后该按钮将运行我试图在“workbook_open”中拥有的代码。

它解决了我的问题,但没有解决上面的问题。因为我的解决方案是简单地跳过“workbook_open”事件。

注意:这也解决了我的另一个问题,当文件被“保护视图”打开时,一些工作表仍然可见,这将被我将在“workbook_open”运行的代码隐藏起来。

我使用的代码:

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)

Call LoadVariables

    
    LoadingForm.show (vbModeless)
    LoadingForm.Caption = "Logging out"
    LoadingForm.Repaint
    Application.ScreenUpdating = False
    
    Call UnProtectSheet("Basic Data")
    FirstTimeOpenToday = "No"
    
    Call ActivateUser("LoginUser")
    
    Application.ScreenUpdating = True
    LoadingForm.Caption = "Changing User"
    LoadingForm.hide
    
End Sub


Sub Login()

    Call LoadVariables
    
    'Resetting so that the file knows that this is the first time opening the file today
    Call UnProtectSheet("Basic Data")
    FirstTimeOpenToday = "No"
    
    'Depending on the file was newly created or not, open applicable LoginForm
    If FirstTimeOpen = "No" Then
        Startpage.show
        Else
        Loginform.show
    End If
End Sub

推荐阅读