计算 Excel vba 中的类型变量,可能吗?

Counting Type Variables in Excel vba, possible?

目前我正在与 excel vba 合作。 我在问自己是否有可能计算在用户定义的 Type 中声明的变量,如下所示。

Public Type NameOfType
   a as string
   b as string
End Type

此处结果为 2。

谢谢

通过VB扩展库

的方法

以编程方式访问 VB假定的项目,您可以

  • 提取其代码模块的声明头并
  • 分析相关代码行

(参考 'Microsoft Visual Basic for Applications Extensibility 5.3' 需要)。

Sub CountTypeVars(ByVal StatementName As String)
    Dim VBAEditor      As VBIDE.VBE              ' VBE
    Dim curProject     As VBIDE.VBProject        ' Projekt
    Dim curComponent   As VBIDE.VBComponent      ' Modul
    Dim curCode        As VBIDE.CodeModule       ' Codeblock des Moduls
    Dim i              As Integer
    ' ========================================
    ' Get the project details in the workbook.
    ' ========================================
    Set VBAEditor = Application.VBE
    Set curProject = VBAEditor.ActiveVBProject
    
    For Each curComponent In curProject.VBComponents    ' check all MODULES
        ' Find the code module for the project (Codeblock in current component/=module).
        Set curCode = curComponent.CodeModule
      
        Dim ii As Long
        ii = curCode.CountOfDeclarationLines
        Dim DeclLines: DeclLines = Split(curCode.Lines(1, ii), vbNewLine)
        Dim cnt As Long, found As Boolean
        cnt = 0
        For i = LBound(DeclLines) To UBound(DeclLines)
            If UCase(DeclLines(i)) Like "* " & UCase(StatementName) & "*" Then
                Debug.Print "** Type Statement : ", DeclLines(i)
                Debug.Print "   Found in Module: ", curComponent.name & vbNewLine & String(50, "-")
                Debug.Print "Line #", "Count #", "Variable(s)" & vbNewLine & String(50, "-")
                found = True: i = i + 1
            End If
            If found And Not UCase(DeclLines(i)) Like "*END TYPE*" Then
                cnt = cnt + 1               ' increment variable counter
                Debug.Print "# " & i + 1, cnt, VBA.Trim(DeclLines(i))
            End If
                
        Next i
        If found Then
            Debug.Print vbNewLine & "** Counted " & cnt & " Type Variables."
            Exit For
        End If
    
    Next
    If Not found Then Debug.Print "** No occurrence of " & StatementName & " found!"
End Sub

示例输出 VB 编辑器的即时 window

打电话,例如CountTypeVars "NameOfType"您可能会得到以下结果:


** Type Statement :         Public Type NameOfType
   Found in Module:         modExample
--------------------------------------------------
Line #        Count #       Variable(s)
--------------------------------------------------
# 4            1            a As String
# 5            2            b As String

** Counted 2 Type Variables.

警告

这种方法将 Type 语句之后的每个代码行都计为 一个 变量;因此不处理其他代码行,例如换行符或注释。