2009-08-19 74 views
4

我正在編寫一個報告工具來記錄各種「合規標準」的Excel文件,其中包括wkb.VBProject.Protection以報告VBA是否被鎖定。如何在VBA中測試Excel工作簿中是否存在VBA?

但是,如何查找工作簿是否有任何項目?

如果我計算

wkb.VBProject.VBComponents.Count - wkb.Worksheets.Count - 1 '(for the workbook) 

,這將使我模塊+類模塊+形式的數字,但我仍然有一個片背後的一些代碼。

在Excel中有沒有一種方法 - 比如Access frm.HasModule - 找出工作簿中是否有VBA代碼?

回答

5

我已經使用了以下內容來統計項目中的行數。它會在ThisWorkbook,代碼模塊,類模塊和表單中選取代碼。

Private Sub countCodeLines() 
    Dim obj As Object 
    Dim VBALineCount As Long 
    For Each obj In ThisWorkbook.VBProject.VBComponents 
     VBALineCount = VBALineCount + obj.CodeModule.CountOfLines 
    Next obj 
    Debug.Print VBALineCount 
End Sub 

不過請注意,如果您的工作簿有Option Explicit被迫那麼這將計爲每個對象兩行(Option Explicit和換行)。如果您知道這一點,並且正在從另一個項目中檢查LOC,那麼您可以簡單地計算對象的數量,將其加倍並測試VBALineCount未超過此數目。

+0

感謝Lunatik,這是完美的。 – 2009-08-19 09:48:35

4

Lunatik的提示後,這是我最後的功能(對他們來說,它可以幫助):

 
Function fTest4Code(wkb As Workbook) As Boolean 
    'returns true if wkb contains VBA code, false otherwise 
    Dim obj As Object 
    Dim iCount As Integer 
    For Each obj In wkb.VBProject.VBComponents 
     With obj.CodeModule 
      '# lines - # declaration lines > 2 means we do have code 
      iCount = iCount + ((.CountOfLines - .CountOfDeclarationLines) > 2) 
     End With 
     If iCount 0 Then Exit For 'stop when 1st found 
    Next obj 
    fTest4Code = CBool(iCount) 
End Function 
7

的Excel 2007+有一個名爲「.HasVBProject」新工作簿屬性,您可以來電諮詢。

對於Excel 2003及更早版本,上述解決方案測試工作簿的任何VBComponents的CodeModule中的代碼行都是適當的。

您應該單獨測試「.CountOfLines」屬性,因爲代碼模塊的聲明部分中的代碼行(通過「.CountOfDeclarationLines」獲取)被Excel視爲「宏代碼」,並且需要保存到宏 - 啓用格式。

Public Function HasVBProject(Optional pWorkbook As Workbook) As Boolean 
' 
' Checks if the workbook contains a VBProject. 
' 
On Error Resume Next 
    Dim wWorkbook As Workbook 
    Dim wVBComponent As VBIDE.VBComponent ' As Object if used with Late Binding 

    ' Default. 
    ' 
    HasVBProject = False 

    ' Use a specific workbook if specified, otherwise use current. 
    ' 
    If pWorkbook Is Nothing _ 
    Then Set wWorkbook = ActiveWorkbook _ 
    Else Set wWorkbook = pWorkbook 
    If wWorkbook Is Nothing Then GoTo EndFunction 

    If (VBA.CInt(Application.Version) >= 12) _ 
    Then 
     ' The next method only works for Excel 2007+ 
     ' 
     HasVBProject = wWorkbook.HasVBProject 
    Else 
     ' Signs the workbook has a VBProject is code in any of the VBComponents that make up this workbook. 
     ' 
     For Each wVBComponent In wWorkbook.VBProject.VBComponents 
      If (wVBComponent.CodeModule.CountOfLines > 0) _ 
      Then 
       ' Found a sign of programmer's activity. Mark and quit. 
       ' 
       HasVBProject = True: Exit For 
      End If 
     Next wVBComponent 
    End If 

EndFunction: 
    Set wVBComponent = Nothing 
    Set wWorkbook = Nothing 
End Function 

荷蘭