Load multidimensional VBA Array from disk
I'm trying to save and then load a multi-dimensional VBA to/from disk.
According to the MSDN website, the number of dimensions are saved as a
descriptor in the file, but I can't figure out how to access/load them.
The example below works, but only because I have hard coded the array
dimensions. The commented out line works in a dynamic sense, but the
array's dimensions are lost in the process.
Here's some sample code:
Sub WriteArray()
Dim file_name As String
Dim file_length As Long
Dim fnum As Integer
Dim values() As Boolean
ReDim values(1 To 5, 1 To 10, 1 To 20)
Dim i As Integer 'Populate the simple array
For i = 1 To 20
values(1, 1, i) = True
Next
' Delete existing file (if any).
file_name = "array.to.file.vba.bin"
On Error Resume Next
Kill file_name
On Error GoTo 0
' Save the file.
fnum = FreeFile
Open file_name For Binary As #fnum
Put #fnum, 1, values
Close fnum
End Sub
Sub ReadArray()
Dim file_name As String
Dim file_length As Long
Dim fnum As Integer
Dim newArray() As Boolean
file_name = "array.to.file.vba.bin" 'txtFile.Text"
fnum = FreeFile
file_length = FileLen(file_name)
'ReDim newArray(1 To file_length) 'This loads the data, but not with the
right dimensions.
ReDim newArray(1 To 5, 1 To 10, 1 To 20) 'This works but with dimensions
hard coded.
'How to re-dim here using the dimensions saved in the file?
Open file_name For Binary As #fnum
Get #fnum, 1, newArray
Close fnum
End Sub
I need to give credit to the VB Helper website because the example above
is based on one they posted here.
No comments:
Post a Comment