如何以编程方式确定VBA中的Option Base的当前设置
如何以编程方式确定VBA中Option Base
的当前设置? Option Base
可以设置为0
或1
,这决定了数组索引是从0
还是1
开始(参见MSDN )。
但是,我看不出有什么简单的方法来找出当前的设置。 我希望可能有一个Option()
函数,我可以传递一个参数,如:
Debug.Print Option("Base")
它会告诉我,但似乎并不存在。
虽然我同意@jonsharpe,如果你使用Lbound Lbound(arr)
和Ubound(arr)
,你不需要在运行时知道这一点,但我认为这是一个有趣的问题。
首先,正确循环一个数组的例子。
For i = LBound(arr) To Ubound(arr) ' do something Next
现在,为了做到你所要求的,你需要访问使用VBIDE
库。 否则称为“Microsoft Visual Basic for Applications扩展性”库。 它提供对IDE和代码的访问。 您可以使用它来发现是否声明了Option Base 1
。 我不build议在运行时尝试。 这在开发过程中作为一种静态代码分析将更有用。
首先,您需要添加对库的引用并授予代码访问权限 。 一旦你这样做了,下面的代码应该做你想要的。
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文档 。
如果使用外接程序是一个选项,@ Mat'sMug和我的开源项目Rubberduck有一个代码检查 ,将显示整个活动项目中的所有实例。
有关该特定检查的更多信息,请参阅此处 。
Function GetBaseOption() As Long Dim arr arr = Array("a") GetBaseOption = LBound(arr) End Sub