【问题标题】:Excel global variable reseted to empty when navigating through workbooks浏览工作簿时 Excel 全局变量重置为空
【发布时间】:2020-11-09 10:45:07
【问题描述】:

我遇到了一个奇怪的问题,我认为它与 Excel 行为有关,而不是与我的代码有关。

我有一个名为“numEtape”的全局变量,它是一个整数。我的代码包含几个步骤,用户必须在工作表上键入数据,然后按下一个按钮,将数据保存在数组中并递增“numEtape”,然后再进行下一步。

代码(简化)如下所示:

Dim numEtape As Integer

Sub AjoutEssai()
    numEtape = 2
    UFPreAjoutInfos.Show 'Unrelated Userform that asks user for more informations, but doesn't modify "numEtape" or call any other macro
    
    Call InterfaceFiller
    
End Sub

Sub InterfaceFiller()
Dim rangedubtn As Range
Dim btnPrecedent As Button

Select Case numEtape
    Case 2
         'Change value of some cells
    Case 3
         'Change value of some cells
    Case 4
         'Change value of some cells
    Case Is >= 5
         'Change value of some cells
    Case Else
         Debug.Print "Error"
End Select

Set rangedubtn = Sheets("Interface").Range("M3")
    Set btnPrecedent = Sheets("Interface").Buttons.Add(rangedubtn.Left, rangedubtn.Top,rangedubtn.Width, rangedubtn.Height) 
    With btnPrecedent
      .OnAction = "mSuivant"
      .Caption = "Suivant"
      .Name = "btnSuivant"
    End With
End Sub

Sub mSuivant()
    numEtape = numEtape + 1
    Call InterfaceFiller
End Sub

我不认为代码本身很重要,因为我第一次调用 AjoutEssai(),所以我可以从中得到什么,因为 numEtape 总是大于 2。 但是,当用户在这些步骤中打开和关闭其他 excel/office 文件(其中没有任何 vba 代码/宏)时,excel 似乎清空了 numEtape,这使得Select Case 转到Case Else。

excel什么时候从内存中删除全局变量,有没有办法防止这种行为发生?

【问题讨论】:

    标签: excel vba


    【解决方案1】:
    • Public numEtape As Long

    一个可行的选择是使用public 这个词,比如public numEtape As Long。 然后,只要打开 Excel 工作簿,该变量就会保存其值。在旧版本的 VBA 中,这个词是 Global (What is the difference between Dim, Global, Public, and Private as Modular Field Access Modifiers?)

    • Dim numEtape As Long

    对于在Sub 或Function 之外使用Dim,代码结束后变量将被清空。只拿这个 sn-p:

    Dim numEtape As Long
    
    Sub MainTest()        
        numEtape = 23        
    End Sub
    

    一旦你运行它并点击End Sub,该变量也会被清空。运行MainTest()后检查:

    Sub PrintingVariable()
        Debug.Print numEtape
    End Sub
    

    如果你想保存值,有两种基本的工作方式:

    • 在 Excel 单元格中写入值
    • 将值写入数据库

    【讨论】:

      猜你喜欢
      • 2015-10-10
      • 1970-01-01
      • 2011-04-16
      • 2017-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-19
      相关资源
      最近更新 更多