我编写了一个类模块appWord_DocumentBeforeClose(ByVal Doc As Document, Cancel As Boolean)
,用于在关闭文档之前将文档保存在SD卡上作为备份。
根据MS网站,以下代码是在模块
中编写的Dim appWord_DocumentBeforeClose As New EventClassModule
Sub Register_Event_Handler()
Set appWord_DocumentBeforeClose.App = Word.Application
End Sub
这是 CLASS模块
中的代码Public oFSO As Scripting.FileSystemObject
Public WithEvents appWord As Word.Application
Private Sub appWord_DocumentBeforeClose(ByVal Doc As Document, Cancel As Boolean)
Dim myPath As String, myFileName As String, fileName As String ', driveLtr As String
myPath = "e:\stamboom\"
If CheckDrive(Left(myPath, 1)) = True Then
fileName = ActiveDocument.Name
myFileName = myPath & Left(ActiveDocument.Name, Len(fileName) - 20) & " " & Format(Now, "yy-mm-dd hhmmss") & ".docm"
ActiveDocument.SaveAs fileName:=myFileName
MsgBox "document saved on " & myPath
Else
MsgBox "drive E doesn't exist"
End If
End Sub
Function CheckDrive(driveLtr As String) As Boolean
Set oFSO = New Scripting.FileSystemObject
If oFSO.DriveExists("E") Then
If oFSO.GetDrive("E").VolumeName = "MY SD" Then
CheckDrive = True
End If
Else
CheckDrive = False
End If
End Function
当我在模块中运行代码时,Dim appWord_DocumentBeforeClose As New EventClassModule
上的VBA编译消息告诉我
未定义用户定义的类型。
有人可以帮助我解决问题吗?
答案 0 :(得分:0)
对于在何处使用哪些术语/名称/标识符似乎有些不清楚...
我假设类模块的名称为EventClassModule
。顶部是声明
Public WithEvents appWord As Word.Application
在常规模块中,请勿使用事件的名称(DocumentBeforeClose),而仅将类模块的名称用于常规模块顶部的声明。 Plus ,分配另一个不同的名称以标识此模块中的类。例如
Dim MyEvents As New EventClassModule
然后,开始事件处理程序的陷阱:
Sub Register_Event_Handler()
Set MyEvents.appWord = Word.Application
End Sub
appWord_DocumentBeforeClose
将在文档尝试关闭时自动触发。如果要添加Open事件或New事件,只要事件处理程序处于活动状态,它们也会自动触发。
为了使事件处理程序在打开文档时自动触发,可以从名为AutoOpen
的宏中调用注册过程。例如
Sub AutoOpen()
Register_Event_Handler
End Sub