簡體   English   中英

檢查 Private Sub Workbook.open() 是否為空

[英]Check if Private Sub Workbook.open() is empty

我有一個用戶需要在打開 Excel 文件后執行宏,並且需要(以編程方式)知道當前 Excel 文件的 Private Sub Workbook.open() 例程是否為空。

有沒有辦法在打開工作簿后將此信息保留在內存中,以便在用戶需要運行他的宏時可以使用此信息。 沿着持久的全局變量的東西將是理想的。 但我不確定這是否可能。

謝謝!

下面的代碼(在常規模塊內)循環遍歷所有 VB 項目組件(包括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 項目模塊,您需要遵循以下 2 個步驟:

步驟1 :添加“對VBA項目對象模型的信任訪問”,轉到開發人員>>宏安全>>然后在對VBA項目對象模型的信任訪問中添加一個V。

第 2 步:添加對 VB 項目的引用,添加“ Microsoft Visual Basic for Applications Extensibility 5.3

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM