更改 VBA 常量的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25126757/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Change value of a VBA constant
提问by Joanna Mikalai
I have a function in which I set a VBA constant as follows:
我有一个函数,我在其中设置了一个 VBA 常量,如下所示:
Const KEY_TEXT As String = "mycystomtext"
Is there a way to change the VBA constant to a different text programmatically?
有没有办法以编程方式将 VBA 常量更改为不同的文本?
I have tried to define:
我试图定义:
Const KEY_TEXT As String = Range("A1").value
but this leads to an error.
但这会导致错误。
回答by
constant, by definition, cannot be changed after initialization. it has to be initialized when defining the variable.
根据定义,常量在初始化后不能更改。它必须在定义变量时进行初始化。
回答by Joanna Mikalai
I am answering my own question which was specifically:
我正在回答我自己的问题,具体是:
Is there a way to change the VBA constant to a different text programmatically?
有没有办法以编程方式将 VBA 常量更改为不同的文本?
Sub replace_run()
Dim s As String
Dim i As Long
Dim VBProj As VBIDE.VBProject
Dim VBComp As VBIDE.VBComponent
Dim CodeMod As VBIDE.CodeModule
With Application
.EnableEvents = False
.ScreenUpdating = False
.DisplayAlerts = False
End With
s = ThisWorkbook.Path
wcodestring = s & "\myfile.xlsm"
Workbooks.Open FileName:=wcodestring
Set wb_code = Application.Workbooks("myfile.xlsm")
Set VBProj_xl = Application.Workbooks("myfile.xlsm").VBProject
Set VBProj = wb_code.VBProject
Set VBComp = VBProj.VBComponents("Module1")
Set CodeMod = VBComp.CodeModule
With CodeMod
For i = 1 To .CountOfLines
If .Lines(i, 1) = "Const KEY_TEXT As String = " & Chr(34) & "mycystomtext" & Chr(34) Then
.ReplaceLine i, "Const KEY_TEXT As String = " & Chr(34) & "mycystomreplace" & Chr(34)
End If
Next i
End With
wb_code.Close SaveChanges:=True
Application.ScreenUpdating = True
End Sub