如何以编程方式确定VBA中Option Base的当前设置

Cal*_*tor 8 excel vba excel-vba

如何以编程方式确定Option BaseVBA中的当前设置?所述Option Base可以被设置为0或者1,这决定数组索引是否在启动01(参见MSDN).

但是,我看不出任何简单的方法来找出当前的设置.我希望可能有一个Option()函数,我可以传递一个参数,如:

Debug.Print Option("Base")
Run Code Online (Sandbox Code Playgroud)

它会告诉我,但它似乎并不存在.

Rub*_*uck 8

虽然我同意@jonsharpe的说法,如果你正在使用Lbound(arr)Ubound(arr),你不需要在运行时知道这一点,但我认为这是一个有趣的问题.

首先,正确循环数组的示例.

For i = LBound(arr) To Ubound(arr)
    ' do something
Next
Run Code Online (Sandbox Code Playgroud)

现在,为了完全按照您的要求进行操作,您需要访问使用该VBIDE库.否则称为"Microsoft Visual Basic for Applications Extensibility"库.它提供对IDE及其代码的访问.您可以使用它来发现是否Option Base 1已声明.我不建议尝试在运行时执行此操作.这在开发期间作为一种静态代码分析会更有用.

首先,您需要添加对库的引用授予代码访问权限.完成后,以下代码应该按照您的意愿执行.

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
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请参阅CodeModule.Find文档.


如果使用加载项是一个选项,@ Mat'sMug和我的开源项目Rubberduck有一个代码检查,它将在整个活动项目中显示所有这些实例.

选项基础1代码检查

有关该特定检查的更多信息,请参见此处.