我正在尝试将工作表单元格的值分配给VBA宏中的常量变量。这个动作背后的逻辑是,最终用户应该在运行宏之前在指定的单元格中输入当前周数。由于这个值将在整个宏中被重复使用,并且我想要保险起见,我试图将其声明为公共常量:
private const thisWeek as Integer = Range("B1")
然而,我收到了一个关于需要常量值的错误消息。那么,在VBA中是否可能像这样声明常量?
Public Const weekRange As String = "$B$1"
Sub Something()
Dim thisWeek As Integer: thisWeek = Range(weekRange).Value
'~~> some codes here
End Sub
帮助文档中指出:在为常量赋值的表达式中,不能使用变量、用户定义函数或内置的Visual Basic函数(如Chr)。
在您的情况下,您需要使用一个变量。
我知道这已经过时了,但我想自己做这件事并想出了这个方法。我使用一个函数:
Function insertPNA(strSource As Long) As String
Dim strResult As String
strResult = Replace(strSource, strSource, ThisWorkbook.Sheets("Audits & Actuals").Range("pnacode").Value)
insertPNA = strResult
End Function
每当我想要 PNA 代码时,我只需输入 insertpna(1)。希望有人发现这样很有用。(明显不一定是“1”,我只是用它来减少打字。)