在 VBA 中的编译时有条件地设置 Const
Set Const Conditionally at compile time in VBA
我想在编译时有条件地设置 const 变量的值。我以为我可以使用 vba 编译器指令 #If #Else 等实现这一点,如下所示,但到目前为止还没有成功:
#If Environ("username") = "myusername" Then
Public Const ErrorHandling As Boolean = False
#Else
Public Const ErrorHandling As Boolean = True
#End If
当我 运行 这段代码时,我收到一个错误,指出 Environ 变量未定义。
这样的事情可能吗?或者我只需要使我的 'ErrorHandling' 变量 Public (不是 Const),并在我的代码初始化时设置它?
在此先感谢,
cjk
您只能在条件 if 语句中使用常量。您可以在 VBAProject 属性中设置它,解释为 here,或者在您的代码中设置它。
Sub TestIt()
#Const Errorhandling = False
#If Errorhandling Then
Debug.Print "Error on"
#Else
Debug.Print "Error off"
#End If
End Sub
您可以找到更多文档 here and a page on pre-defined constants
更新:正如共产国际正确指出的那样,我的声明只有常量并不完全正确,参见section 5.6.16.2 of the language spec
我想在编译时有条件地设置 const 变量的值。我以为我可以使用 vba 编译器指令 #If #Else 等实现这一点,如下所示,但到目前为止还没有成功:
#If Environ("username") = "myusername" Then
Public Const ErrorHandling As Boolean = False
#Else
Public Const ErrorHandling As Boolean = True
#End If
当我 运行 这段代码时,我收到一个错误,指出 Environ 变量未定义。
这样的事情可能吗?或者我只需要使我的 'ErrorHandling' 变量 Public (不是 Const),并在我的代码初始化时设置它?
在此先感谢,
cjk
您只能在条件 if 语句中使用常量。您可以在 VBAProject 属性中设置它,解释为 here,或者在您的代码中设置它。
Sub TestIt()
#Const Errorhandling = False
#If Errorhandling Then
Debug.Print "Error on"
#Else
Debug.Print "Error off"
#End If
End Sub
您可以找到更多文档 here and a page on pre-defined constants
更新:正如共产国际正确指出的那样,我的声明只有常量并不完全正确,参见section 5.6.16.2 of the language spec