1

我正在尝试保存然后将多维 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 网站,因为上面的示例基于他们在此处发布的示例。

4

1 回答 1

1

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

第一个。写入文件。

Boolean我的数组类型有一些问题。它不起作用,但它正在与Variant type. 我将打开模式从 更改BinaryRandom。此外,我根据此 MSDN 信息Len parameter使用了value 。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. 我根据此 MSDN 信息将文件打开类型更改为RandomfromBinary并使用最大可能值。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

变量值的屏幕截图。

在此处输入图像描述

于 2013-08-08T06:05:46.523 回答