1

多次元 VBA 配列を保存してから、ディスクとの間で読み込もうとしています。MSDN の Web サイトによると、次元数は記述子としてファイルに保存されますが、それらにアクセス/ロードする方法がわかりません。以下の例は機能しますが、配列の次元をハードコーディングしたためです。コメントアウトされた行は動的な意味で機能しますが、配列の次元はその過程で失われます。

サンプルコードは次のとおりです。

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 Web サイトの功績を称える必要があります。

4

1 に答える 1

1

正直なところ、配列をテキスト ファイルに書き込むことができるこの VBA テクニックを知りませんでした。あるいは、忘れてしまったのかもしれません。:) したがって、私はそれに飛び込みました。

1位。ファイルへの書き込み。

Boolean配列の型に問題があります。動作していませんが、動作していVariant typeます。そして、オープンモードを から に変更しBinaryましたRandom。また、この MSDN 情報によると、価値のあるものを使用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

2番目。ファイルからの読み取り

配列は になりますVariant type dynamicこの MSDN 情報に従って、ファイルのオープン タイプをRandomからに変更し、可能な最大値Binaryで使用しました。Len parameter

これは改善された 2 番目のサブです。

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 に答える