Ribbon onLoad sub中存在ActiveDocument错误4248



我有一个带有自定义功能区的全局模板。当我试图打开文档时,我收到错误4248,它声称由于没有打开任何文档,命令无法运行。

onLoad子中的代码正在检查以确保活动文档不是模板或Normal.dotm,因为我不希望通过调用的过程将文档变量写入这些文件。这在Word 2013中运行良好,但我注意到,在Word 2016中,ribbon-onLoad过程似乎在Word中的文档打开之前运行。我已经将问题定位到ActiveDocument.Name行,在那里我可以捕获错误并继续下一步,但这无助于我在确定这不是全局模板文档或Normal.dotm.后运行额外的代码

Public myRibbonNewNormal As IRibbonUI
Public bVisible As Boolean
Dim bDocSaved As Boolean
Sub onLoad_newNormal(ribbon As IRibbonUI)
Set myRibbonNewNormal = ribbon
On Error GoTo onLoadError
If ActiveDocument.Name = "Styles.dotm" Or ActiveDocument.Name = 
"newNormal.dotm" Then
Exit Sub
ElseIf ActiveDocument.ReadOnly Then
Exit Sub
Else
'Call checkDocType
Call uncheckUpdateStyles
Call removeClientFooter
Call checkTemplate
If bDocSaved <> True Then
Call preventSave
Else
'do nothing
End If
End If
Exit Sub
onLoadError:
If Err.Number = 0 Then
Resume Next
ElseIf Err.Number = 5 Then
Resume Next
ElseIf Err.Number = 5825 Then
Resume Next
ElseIf Err.Number = 5903 Then
Resume Next
'ElseIf Err.Number = 5155 Then
'  Resume Next
ElseIf Err.Number = 4248 Then
Resume Next
Else
MsgBox "This error is in the onLoad sub in the newNormal RibbonControl" _
& vbCrLf & vbCfLf & "Error: " & Err.Number & vbCrLf & Err.Description, , 
"Error"
End If
End Sub

(请原谅我的错误处理。当我写这段代码时,我很匆忙,只是还没有抽出时间来正确处理。)

有没有一种方法可以让我等待执行onLoad子文件,直到Word打开文档(只需双击)?我确信我在这里遗漏了一些东西,但我很难在网上找到任何关于这件事的信息。

将代码移动到应用程序级事件处理程序。每次打开新文档时,代码都会运行,但如果需要,可以进行补救(请参阅代码注释)。

创建一个新的类模块,并将该类模块命名为EventMngr

在类模块中放置以下代码:

Public WithEvents appevent As Application
Private Sub appevent_DocumentOpen(ByVal Doc As Document)
'This code will only allow the event to fire once
Static hasOpened As Boolean
If hasOpened Then Exit Sub Else hasOpened = True
'Place Code Here...
End Sub

然后您可以将该行放在任何其他子系统/功能之前的正常模块中

'application level event handler
Public myEventHandler As New EventMngr

最后,将其放在Ribbon OnLoad子文件中:

'application event handler
Set myEventHandler.appevent = Application

与前面的答案类似,但可能更简单的是将autoopen和autonew过程添加到代码中,并在这些过程中捕获活动文档,而不是onload过程。

最新更新