我正在尝试保存然后将多维 VBA 数组加载到磁盘/从磁盘加载。根据MSDN website,维数作为描述符保存在文件中,但我不知道如何访问/加载它们。下面的示例有效,但这只是因为我对数组维度进行了硬编码。注释掉的行在动态意义上起作用,但在此过程中会丢失数组的尺寸。
这是一些示例代码:
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
我需要感谢 VB Helper 网站,因为上面的示例基于他们在此处发布的示例。