的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
荷蘭
感謝Lunatik,這是完美的。 – 2009-08-19 09:48:35