• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 610
  • Last Modified:

Difference between an array defined with "Static" keyword and "Dim" keyword?

hi,

Is there any difference between the following two statements?

Static strarray() As String
Dim strarray() As String

I tried to change Dim strarray() As String to Static strarray() As String in the below code. I dont see the difference this way. Can anybody explain? Thanks
       


Private Sub Form_Load()
    Dim strarray() As String
        
    ReDim strarray(2) As String
    
    strarray(0) = "1"
    strarray(1) = "2"
           
    For i = 0 To UBound(strarray) - 1
        MsgBox (strarray(i))
    Next
End Sub

Open in new window

0
ipjyo
Asked:
ipjyo
  • 2
1 Solution
 
thoffmanCommented:
Static causes the variable to keep the value between function calls. It basically "remembers" the value of the array when the function exits instead of resetting it each time it's called. I've modified the function to show how it would behave (I changed the variable to a long to make it easier to see).
 
If you keep it as dim, the code will return the following every time it's run:
1
2

On the other hand, if you make it static, the first time it's run, it returns:
1
2

Then, the second time it's run, since strarray(0) is set to 1, it returns:
2
3

And so on...

Private Sub Form_Load()
    Dim strarray() As long
        
    ReDim strarray(2) As long
    
    strarray(0) = strarray(0) + 1
    strarray(1) = strarray(0) + 1
           
    For i = 0 To UBound(strarray) - 1
        MsgBox (strarray(i))
    Next
End Sub

Open in new window

0
 
thoffmanCommented:
By the way, I just realized that you had that in a Form_Load, so static wouldn't make much sense since the function is only called once anyway. It would be better in a button click function.
0
 
ipjyoAuthor Commented:
Thanks for the clarification.
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now