【问题标题】:VBA Excel - Mantaining Public Variables With Button PressVBA Excel - 使用按钮保持公共变量
【发布时间】:2015-04-20 07:15:06
【问题描述】:

我正在尝试创建一个包含一堆 o 常量字符串的文档。

我已经在这样的模块中声明了 Public:

Public Abc As String

在“ThisWorkbook”中,我运行以下代码来初始化 de 变量

Private Sub Workbook_Open()

    Abc = "C5"

End Sub

我有 Buttons 编码来改变一些值,比如:

If Range(Abc) = "" Then
    Range(Abc) = 1
Else
    Range(Abc) = Range(Abc) + 1
End If

当我使用此代码运行按钮时:

Sub BotaoNovoDia()

i = 3
While i <= 33
    If Cells(i, 11) = "" Then
        Cells(i, 11) = Range(Apresentacao)
        Cells(i, 12) = Range(Aceitacao)
        Cells(i, 13) = Range(Aceitou)
        Cells(i, 31) = Range("D41")

        Cells(i, 11).Interior.Color = Range(Apresentacao).Interior.Color
        Cells(i, 12).Interior.Color = Range(Aceitacao).Interior.Color


        If Range("K34") < 0.65 Then
            Range("K34").Interior.Color = vbRed
        Else
            Range("K34").Interior.Color = vbGreen
        End If

        If Range("L34") < 0.45 Then
            Range("L34").Interior.Color = vbRed
        Else
            Range("L34").Interior.Color = vbGreen
        End If

        Range(Aceitou) = 0
        Range(Rejeitou) = 0
        Range(NaoApres) = 0
        End
    Else
        i = i + 1
    End If
Wend
End Sub

我尝试再次运行第一个按钮,但出现错误提示:“运行时错误'1004':对象'_Global'的方法'范围'失败” 调试按钮将我带到尝试访问公共变量值的第一行。我可以做些什么来维护公共变量中的值?

【问题讨论】:

  • 您可以在工作簿中使用Name 来存储值,这甚至会在运行时持续存在。

标签: excel vba


【解决方案1】:

使用命名范围是个好主意;但是你的公开声明没有理由不起作用 - 除了那个讨厌的 End 声明。(我错过了第一次通读...)

但是,您的每个功能的范围都不清楚,例如哪个工作表是 Range 所引用的,所以如果一个函数在另一个工作表上工作,按下触发“更改”的按钮可能会引用一个不喜欢该引用的不同位置。

例如您的范围应该类似于SomeWorkbook.TheWorksheet.Range(&lt;range&gt;),当您更改单元格值时,您应该使用.Value 以确保没有歧义 - 您会从这里搜索知道错误 1004 是描述性最少的错误代码.. .

【讨论】:

    【解决方案2】:

    当您调用 End(本身,而不是 End If 的一部分等)时,您会清除您的全局变量。

    不要使用 End。

    【讨论】:

    猜你喜欢
    • 2014-03-15
    • 2021-03-27
    • 1970-01-01
    • 2015-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-25
    • 2020-06-10
    相关资源
    最近更新 更多