VBA 中的常量引用标签

Constant in VBA referencing a label

VBA 的新手。试图创建一个引用工作表中命名列的常量,但出现错误。这是你可以在 VBA 中做的事情还是我的语法错误?

示例

Public Const ColNum As Integer = [SomeColumn].Column

编译错误告诉你哪里出了问题:需要常量表达式

换句话说,正如@roryap 提到的,您只能为常量表达式使用文字值,不能为其分配任何必须在运行时求值的内容。一种可能的解决方法是使用常量字符串(即您的范围的 Name)并根据需要分配到其他地方

从您的 parent/main 过程调用另一个过程,该过程将分配给模块级或 public 变量

Option Explicit
Const MyColumnName as String = "Dave_Column"
Dim ColNum as Integer

Sub main()

    Call InitializeVariables

    'The rest of your code ...
    MsgBox ColNum

End Sub

Sub InitializeVariables()
    'Use this procedure to assign public/module scope variables if needed
    ColNum = Range(MyColumnName).Column

End Sub

或者,ColNum 可以是一个带有可选参数的函数,当留空时,return 范围基于常量字符串,或者您可以指定一个不同的范围 name/address到 return 另一个列号:

Option Explicit
Const MyColumnName as String = "Dave_Column"
Sub main()

    MsgBox ColNum

    MsgBox ColNum("H1")

End Sub
Function ColNum(Optional name$) As Integer

    If name = vbNullString Then 
        name = MyColumnName
    End If

    ColNum = Range(name).Column


End Function

注意:如果命名范围不存在,这将失败:)

常量必须能够在代码编译(即在运行之前)时计算

这没问题:

Const A as Long = 10 'constant value

还有这个:

Const B As Long = A 'from another constant

甚至

Const B As Long = A * 10 'constant expression

但不是这个:

Const B As Long = ActiveSheet.Columns.Count 'errors

因为ActiveSheet.Columns.Count只能在运行时确定