简体   繁体   中英

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.

I have been working on a routine for excel. I am a (very) novice coder.

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.

I think the problem occurs when another page is selected in the multipage, the static variable is cleared.

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).
  • 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.

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. You will generally want to keep the scope of your variables to the lowest level required. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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