我有一个Word VBA应用程序,它处理各种文档以使它们具有一致的外观(它们从另一个SW工具导出)。每种文档类型都有一个“知道”如何进行转换的类文件。如果添加了新的文档类型,我将创建一个新的类文件,然后必须更新几个过程以添加对新类的引用。我想自动发现和使用类文件的过程(它们都遵循命名约定)。以下是我必须收集文件的引用:
Dim olVBCodeMod As VBComponents
Dim olaClasses() As VBComponent
Dim olVBCodeCmpt As VBComponent
Const slCLASS_NAME_PREFIX = "clsXXXX"
Set olVBCodeMod = Application.VBE.ActiveVBProject.Collection.Item("Normal").VBComponents
ReDim olaClasses(0)
For Each olVBCodeCmpt In olVBCodeMod
If olVBCodeCmpt.Type = vbext_ct_ClassModule Then
If InStr(olVBCodeCmpt.Name, slCLASS_NAME_PREFIX) = 1l Then
Set olaClasses(UBound(olaClasses)) = olVBCodeCmpt
ReDim Preserve olaClasses(UBound(otaClasses) + 1)
End If
End If
Next
ReDim Preserve olaClasses(UBound(otaClasses) - 1)
不幸的是,我没有看到从引用类文件到能够在类文件中运行过程的任何方法,即olaClasses(0).function1?
我的后备方法是创建一个子类,它返回一个对象数组(作为参数传入),并引用每个类:
Set olaClasses(0) = New clsXXXX
这有用,例如olaClasses(0).function1给了我正确的响应,但是能够自动发现类文件会很好......
答案 0 :(得分:0)
感谢您的评论,我想我现在和你在一起。所以你想要这样的东西:
Public Sub FormatActiveDocument()
Dim className as String
className = "cls" & [ActiveDocumentDocType or whatever]
Dim docClass as Object
Set docClass = GetClass(className)
If (obj is Nothing) Then MsgBox("ERROR: Missing VBA class '" & className & "'.")
docClass.FormatDocument '<-- MAGIC HAPPENS HERE (via late binding)
End Sub
Private Function GetClass(className as String) as Object
Dim classes() as VBComponent
Set classes = ' [YOUR CODE]
For each obj as VBComponent In classes
If (obj.Name = className) Then
GetClass = obj
Exit Function
End If
Next
GetClass = Nothing
End Function