0

我有一个 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?

我的后备方法是创建一个 sub,它返回一个对象数组(作为参数传入),并引用每个类:

Set olaClasses(0) = New clsXXXX

这行得通,例如 olaClasses(0).function1 给了我正确的响应,但能够自动发现类文件会很整洁......

4

1 回答 1

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
于 2013-03-22T01:33:37.950 回答