虽然我同意 @jonsharpe 的观点,如果您使用的是 Lbound(arr) 和 Ubound(arr),则无需在运行时知道这一点,但我认为这是一个有趣的问题。
首先,一个正确循环数组的示例。
For i = LBound(arr) To Ubound(arr)
' do something
Next
现在,为了完全按照您的要求进行操作,您需要使用VBIDE 库进行访问。也称为“Microsoft Visual Basic for Applications Extensibility”库。它提供对 IDE 和其中代码的访问。您可以使用它来发现是否已声明 Option Base 1。我不建议在运行时尝试这样做。这在开发过程中作为一种静态代码分析会更有用。
首先,您需要add a reference to the library 和grant the code access to itself。完成此操作后,以下代码应该可以执行您想要的操作。
Public Sub FindOptionBase1Declarations()
Dim startLine As Long
startLine = 1
Dim startCol As Long
startCol = 1
Dim endLine As Long
endLine = 1 ' 1 represents the last line of the module
Dim endCol As Long
endCol = 1 ' like endLine, 1 designates the last Col
Dim module As CodeModule
Dim component As VBComponent
For Each component In Application.VBE.ActiveVBProject.VBComponents ' substitute with any VBProject you like
Set module = component.CodeModule
If module.Find("Option Base 1", startLine, startCol, endLine, endCol, WholeWord:=True, MatchCase:=True, PatternSearch:=False) Then
Debug.Print "Option Base 1 turned on in module " & component.Name
' variables are passed by ref, so they tell us the exact location of the statement
Debug.Print "StartLine: " & startLine
Debug.Print "EndLine: " & endLine
Debug.Print "StartCol: " & startCol
Debug.Print "EndCol: " & endCol
' this also means we have to reset them before we look in the next module
startLine = 1
startCol = 1
endLine = 1
endCol = 1
End If
Next
End Sub
请参阅CodeModule.Find documentation 了解更多信息。
如果可以选择使用加载项,@Mat'sMug 和我的开源项目 Rubberduck 有一个 Code Inspection,它将显示整个活动项目中的所有实例。
See this for more information on that particular inspection.