更改VBA常量的值

时间:2014-08-04 20:12:07

标签: excel excel-vba vba

我有一个函数,我按如下方式设置VBA常量:

Const KEY_TEXT As String = "mycystomtext"

有没有办法以编程方式将VBA常量更改为其他文本?

我试图定义:

Const KEY_TEXT As String = Range("A1").value 

但这会导致错误。

2 个答案:

答案 0 :(得分:4)

根据定义,

常量在初始化后无法更改。它必须在定义变量时初始化。

答案 1 :(得分:4)

我正在回答我自己的问题:

有没有办法以编程方式将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