简体   繁体   English

在 Excel 中使用 VBA - Static 多页 object 发生更改事件(更改页面)时不保留变量

[英]Using VBA in Excel - Static variable not retained when Multipage object has change event (changing pages)

I am having trouble with losing static variables within an Excel user form.我无法在 Excel 用户表单中丢失 static 个变量。

I have been working on a routine for excel. I am a (very) novice coder.我一直在为 excel 做例程。我是一个(非常)新手编码器。

I am attempting to populate a cell range to an array.我正在尝试将单元格范围填充到数组中。 I have been able to do this without issue.我已经能够毫无问题地做到这一点。

However, when I attempt to store the array as a *static * variable, the variable is not retained for as long as I want it to be.但是,当我尝试将数组存储为 *static * 变量时,只要我希望它保留,变量就不会保留。

I think the problem occurs when another page is selected in the multipage, the static variable is cleared.我认为问题发生在多页中选择另一个页面时,static 变量被清除。

Code is something like this:代码是这样的:


Sub UserForm_Initialize ()

static myArray () as variant

dim myRange as range

set myRange = [namedrange]

myArray=myRange

msgbox myArray(0,0) 'this works fine

call OtherSub

end sub

sub OtherSub ()

msgbox myArray(0,0) 'this returns a blank

end sub

The first sub of code shows the array element just fine.第一个子代码很好地显示了数组元素。 The array element is blank in the second sub.第二个子数组元素为空。

I have tried:我努力了:

  • Declaring the array as a public variable, but this returns an error (I think that variables within user forms are private by default and cannot be changed).将数组声明为公共变量,但这会返回错误(我认为用户 forms 内的变量默认是私有的,无法更改)。
  • using a very small variable (a simple string)使用一个非常小的变量(一个简单的字符串)
  • writing code in a module before opening the user form (variable is not retained).在打开用户表单之前在模块中编写代码(不保留变量)。

I am aware that I can just write data to a cell range, but this would defeat the purpose.我知道我可以只将数据写入单元格范围,但这会破坏目的。 I was hoping to avoid multiple instances of reading large arrays from the worksheet.我希望避免从工作表中读取大 arrays 的多个实例。

This might explain it a bit clearer.这可能会解释得更清楚一些。 Moving MyArray outside of the Procedure will set it's scope to a Module Level, making it usable through other subs within that module.将 MyArray 移到过程之外会将其 scope 设置为模块级别,使其可通过该模块中的其他子程序使用。 You will generally want to keep the scope of your variables to the lowest level required.您通常希望将变量的 scope 保持在所需的最低级别。 The other option would be to pass your variable as a parameter to your other procedure.另一种选择是将您的变量作为参数传递给您的其他过程。

Option Explicit

Dim MyArray() As Variant            ' Private Module Level Scope
Public ExampleVariable As String    ' Public Module Level Scope (Not required, just showing an example.)

Sub UserForm_Initialize()
   
    Dim myRange As Range            ' Procedure Level Scope
    Set myRange = [namedrange]
    
    MyArray = myRange
    MsgBox MyArray(0, 0) 'this works fine

    Call OtherSub
End Sub

Sub OtherSub()
    MsgBox MyArray(0, 0) 'this returns a blank
End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM