从磁盘加载多维VBA阵列

时间:2013-08-07 21:58:42

标签: arrays vba multidimensional-array

我正在尝试保存,然后将多维VBA阵列加载到磁盘或从磁盘加载。根据{{​​3}},维度的数量在文件中保存为描述符,但我无法弄清楚如何访问/加载它们。下面的示例有效,但仅仅因为我对数组维度进行了硬编码。注释掉的行在动态意义上有效,但在此过程中数组的维度会丢失。

以下是一些示例代码:

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网站,因为上面的示例基于他们发布的MSDN website

1 个答案:

答案 0 :(得分:1)

老实说,我不知道这种允许将数组写入文本文件的VBA技术。或许我忘了它。 :)因此我潜入其中。

<强>第一。写入文件。

我的数组Boolean类型有些问题。它不起作用,但它与Variant type一起使用。我将开放模式从Binary更改为Random。此外,我根据this MSDN information使用了Len parameter Open Statement的值。

这是第一个改进的子项:

Sub WriteArray()

    Dim file_name As String
    Dim file_length As Long
    Dim fnum As Integer

    Dim values() As Variant
    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

    '<<<<<<< this is new >>>>>>>
    Dim arrLen As Long
        arrLen = (2 + 3 * 8) + (5 * 10 * 20 * 3)

    '<<<<<<< this is changed >>>>>>>
    Open file_name For Random As #fnum Len = arrLen
    Put #fnum, 1, values
    Close fnum

End Sub

<强>第二。从文件中读取

我们的数组将是Variant type dynamic。我将文件打开类型从Random更改为Binary,并根据this MSDN information使用Len parameter最大可能值。

这是第二个改进的:

Sub ReadArray()
    Dim file_name As String
    Dim fnum As Integer
    Dim newArray() As Variant

    file_name = "array.to.file.vba.bin" 'txtFile.Text"
    fnum = FreeFile

    '<<<<<<< this is new >>>>>>>
    Dim lenAAA
        lenAAA = 32767  '>>> MAX possible value

    '<<<<<<< this is changed >>>>>>>
    Open file_name For Random As #fnum Len = lenAAA
    Get #fnum, 1, newArray
    Close fnum

End Sub

变量值的屏幕截图。

enter image description here