在启用编辑时,Workbook_Open()sheet.activate受保护视图中的错误

当文件处于保护模式 (因为从Internet下载时,我遇到了包含在Workbook_Open()中的 sheets.activate的问题。 只要您“启用编辑”Workbook_Open()执行,并出现错误。

如果我使用这个代码:

Private Sub Workbook_Open() Sheets(2).Activate End Sub 

我有这个错误: 运行时错误1004激活Worksheet类的方法失败

在其他一些讨论中,我尝试使用Workbook_Activate()方法,该方法在我的所有项目中只有一个简单的激活。 前面的例子可以修复,如果我使用:

 Private Sub Workbook_Open() a = True End Sub Private Sub Workbook_Activate() If a Then Sheets(2).Activate a = False End If End Sub 

但它部分解决了这个问题,这段代码可以工作,但下一次我有另一个sheets.activate在我的项目中错误再次出现,(即如果我点击一个button进入面板或如果我运行其他例程)。

这个错误只在第一次打开文件时出现,如果你停止debugging器,closures文件而不保存并重新打开文件错误不会再出来,但我会避免它第一次出来

提前致谢

这看起来像是一个已知的问题:
退出受保护的视图时,对象模型调用可能会从WorkbookOpen事件失败

它说 …

parsing度
您可以通过以下任一方式解决问题:

  1. 如果打开工作簿的位置受信任,请将该位置添加到Excel的受信任位置。

  2. 将WorkbookOpen事件之外的对象模型调用推迟到WorkbookActivate事件。

推迟对象模型调用的代码示例

 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