|
找到了一个完整的代码,遍历所有子程序和函数
Sub GetVBAProcedures()
'声明访问Excel工作簿的变量
Dim app As Excel.Application
Dim wb As Excel.Workbook
Dim wsOutput As Excel.Worksheet
Dim sOutput() As String
Dim sFileName As String
'声明访问工作簿中宏的变量
Dim vbProj As VBIDE.VBProject
Dim vbComp As VBIDE.VBComponent
Dim vbMod As VBIDE.CodeModule
'声明其它变量
Dim iRow As Long
Dim iCol As Long
Dim iLine As Integer
Dim sProcName As String
Dim pk As vbext_ProcKind
Set app = Excel.Application
'创建新工作簿用于输出数据
Set wsOutput = app.Workbooks.Add.Worksheets(1)
'遍历打开的所有工作簿
For Each vbProj In app.VBE.VBProjects
On Error Resume Next
sFileName = vbProj.Filename
If Err.Number <> 0 Then sFileName = "文件没有保存"
On Error GoTo 0
'初始化输出数组
ReDim sOutput(1 To 2)
sOutput(1) = sFileName
sOutput(2) = vbProj.Name
iRow = 0
'检查是否为受保护的工程
On Error Resume Next
Set vbComp = vbProj.VBComponents(1)
On Error GoTo 0
If Not vbComp Is Nothing Then
'遍历工程中的每个组件
For Each vbComp In vbProj.VBComponents
'找到代码模块
Set vbMod = vbComp.CodeModule
'浏览代码模块,查找程序
iLine = 1
Do While iLine < vbMod.CountOfLines
sProcName = vbMod.ProcOfLine(iLine, pk)
If sProcName <> "" Then
iRow = iRow + 1
ReDim Preserve sOutput(1 To 2 + iRow)
sOutput(2 + iRow) = vbComp.Name & ": " & sProcName
iLine = iLine + vbMod.ProcCountLines(sProcName, pk)
Else
'这行没有程序,到下一行
iLine = iLine + 1
End If
Loop
Set vbMod = Nothing
Set vbComp = Nothing
Next
Else
ReDim Preserve sOutput(1 To 3)
sOutput(3) = "工程被保护"
End If
If UBound(sOutput) = 2 Then
ReDim Preserve sOutput(1 To 3)
sOutput(3) = "工程中没有代码"
End If
'定义输入位置并输出
If Len(wsOutput.Range("A1").Value) = 0 Then
iCol = 1
Else
iCol = wsOutput.Cells(1, wsOutput.Columns.Count).End(xlToLeft).Column + 1
End If
wsOutput.Cells(1, iCol).Resize(UBound(sOutput) + 1 - LBound(sOutput)).Value = WorksheetFunction.Transpose(sOutput)
Set vbProj = Nothing
Next
wsOutput.UsedRange.Columns.AutoFit
End Sub |
|