Jens
Jens

Reputation: 145

VB: Saving an array

This is probably trivial but I couldn't find an answer via Google.

In Visual Basic, is it possible to save an array to a variable and then restore that array to its previous self by setting it equal to that variable?

Example:

Dim SomeArray(20) As Integer

X = SomeArray

{Do stuff to the SomeArray}

SomeArray = X

I've tried this by using a variable X defined as a Variant, but that gives a compile error. Any suggestions?

EDIT

Thank you everyone for trying to help me out. I've posted my test VBA code below. I get a compile error already at the statement "X = SomeArray". I hope one of you can tell me where my error lies. Here's the code:

Dim SomeArray(), X() As Integer

Sub Macro1()

ReDim SomeArray(1 To 20)

X = SomeArray

For i = 1 To 20
  SomeArray(i) = i
Next i

SomeArray = X

For i = 1 To 20
  MsgBox "SomeArray(" & i & ") = " & SomeArray(i)
Next i

End Sub

Upvotes: 0

Views: 86

Answers (2)

dbmitch
dbmitch

Reputation: 5386

Not sure what you're doing in your example - you're not even using X

I assume you want to test transferring SomeArray into the X array

I'd just use a variant for X and do this

Dim SomeArray()
Dim X As Variant

Sub Macro1()

    ReDim SomeArray(1 To 20)

    For i = 1 To 20
      SomeArray(i) = i
    Next i

    X = SomeArray

    For i = 1 To 20
      MsgBox "x(" & i & ") = " & X(i)
    Next i

End Sub

Upvotes: 0

cyboashu
cyboashu

Reputation: 10443

Just declare data type for first array as Scott said. Seems you are overly confused now, take a deep breath and copy paste this code. :) Revisit it after some time and everything will be clear. :)

Dim SomeArray() As Integer, X() As Integer

Sub Macro1()

ReDim SomeArray(1 To 20)

X = SomeArray

For i = 1 To 20
  SomeArray(i) = i
Next i

SomeArray = X

For i = 1 To 20
  MsgBox "SomeArray(" & i & ") = " & SomeArray(i)
Next i

End Sub

Upvotes: 1

Related Questions