我有一个用户需要在打开Excel文件后执行宏,并且需要知道(以编程方式)当前Excel文件的Private Sub Workbook.open()例程是否为空。
在打开工作簿之后是否有任何方法可以将此信息保留在内存中,以便在用户需要运行其宏时,此信息可用。沿着持久的全局变量的东西将是理想的。但我不确定它是否可能。
谢谢!
答案 0 :(得分:1)
下面的代码(在常规模块中)循环遍历所有VB Project组件(包括ThisWorkbook
模块),并检查模块名称是否为“ThisWorkbook”。
一旦找到“ThisWorkbook”模块,它会检查该模块中的代码行总数,如果它为0,则会引发MsgBox
它为空。如果不是,则检查它是否可以在代码中找到“Workbook_Open”字符串。如果是,则计算“Workbook_Open”行与最近的“End Sub”行之间的代码行(不是空行)。
Check_WorkBookModule_Contents 代码
Option Explicit
Sub Check_WorkBookModule_Contents()
Const PROC_NAME = "ThisWorkbook"
Dim VBProj As VBIDE.VBProject
Dim VBComp As VBIDE.VBComponent
Dim CodeMod As VBIDE.CodeModule
Dim i As Long, j As Long, SubLinesCount As Long
Dim ModuleCodeLinesCount As Long
Set VBProj = ActiveWorkbook.VBProject
' loop through all modules, worksheets and other objects in VB Project
For Each VBComp In VBProj.VBComponents
Set CodeMod = VBComp.CodeModule
Debug.Print CodeMod.Name ' <-- for debug
If CodeMod.Name Like PROC_NAME Then ' <-- check if module name is "ThisWorkbook"
' if total of code lines in "ThisWorkbook" module is empty
If CodeMod.CountOfLines = 0 Then
MsgBox CodeMod.Name & " module is empty"
Exit Sub
End If
SubLinesCount = 0 ' reset counter
' loop through all code lines inside current module
For i = 1 To CodeMod.CountOfLines
If Len(CodeMod.Lines(i, 1)) > 0 Then
' if the name of current sub is found within the current code line
If CodeMod.Lines(i, 1) Like "*Workbook_Open*" Then
For j = i + 1 To CodeMod.CountOfLines
If Len(CodeMod.Lines(j, 1)) > 0 And Not CodeMod.Lines(j, 1) Like "End Sub*" Then
SubLinesCount = SubLinesCount + 1
End If
Next j
If SubLinesCount > 0 Then
MsgBox CodeMod & " module, has an event of 'Workbook_Open' , with total of " & SubLinesCount & " lines of code"
Exit Sub
Else
MsgBox CodeMod & " module, has an event of 'Workbook_Open' , but it's empty !"
Exit Sub
End If
End If
End If
Next i
End If
Next VBComp
End Sub
注意:要访问VB项目模块,您需要按照以下两个步骤操作:
第1步:添加“信任访问VBA项目对象模型”,转到开发人员&gt;&gt;宏安全&gt;&gt;然后将V添加到对VBA项目对象模型的Trust访问。
第2步:添加对VB项目的引用,添加“ Microsoft Visual Basic for Applications Extensibility 5.3 ”