【问题标题】:Assigning the value of a worksheet cell to a constant将工作表单元格的值分配给常量
【发布时间】:2017-05-30 00:32:38
【问题描述】:

我正在尝试将工作表单元格的值分配给 VBA 宏中的常量变量。该操作背后的逻辑是最终用户应该在运行宏之前在指定单元格中输入当前周。由于该值将在整个宏中重复使用,并且我想安全起见,因此我尝试将其声明为公共常量:

private const thisWeek as Integer = Range("B1")

但是,我收到一条关于需要常量值的错误消息。那么,甚至可以在 VBA 中声明这样的常量吗?

【问题讨论】:

    标签: vba excel


    【解决方案1】:

    不,这是不可能的。正如这个词所暗示的,它应该是常量

    解决方法:

    Public Const weekRange As String = "$B$1"
    

    然后在你的代码中:

    Sub Something()
        Dim thisWeek As Integer: thisWeek = Range(weekRange).Value
    '~~> some codes here
    End Sub
    

    【讨论】:

      【解决方案2】:

      来自帮助:您不能在分配给常量的表达式中使用变量、用户定义函数或内部 Visual Basic 函数(例如 Chr)。

      在你的情况下,你必须使用一个变量。

      【讨论】:

        【解决方案3】:

        我知道这是旧的,但我想自己做这个并想出了这个。我使用一个函数:

        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” obvs,我只是用它来减少打字。)

        【讨论】:

        • 我收到“模块之间的循环引用”错误。
        猜你喜欢
        • 1970-01-01
        • 2018-08-05
        • 2017-09-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多