首页 > 解决方案 > VBA:为什么打开随机语句失败?

问题描述

我有一个简单的函数,可以随机访问一个文件并在指定位置读取 4 个字节。

我用来选择记录的代码是:

    Open "C:\MyFile.bin" For Random Access Read As #file_nr Len = 4
    rec_position = 23         '(this is an example)
    Get #file_nr, rec_position, buff
    Close #file_nr

其中变量“buff”以这种方式声明:

    Dim buff(0 To 3) As Byte   'fixed size array declaration
and it works fine.

但是......如果我不想概括为固定的 4 字节记录长度,而是使用“rec_len”字节的记录长度,我以这种方式声明“buff”变量:

    Dim rec_len As Long       'length of the record, in bytes
    Dim buff() As Byte        'dynamic declaration of array to store one record
    ...(omissis)...
    ReDim buff(0 To rec_len - 1)

现在程序坚持“get”指令并给我这个错误:运行时错误7“内存不足”。

但是我有足够的可用内存,代码很短,我使用了一个很小的 ​​rec_len (rec_len=4),我重新启动了我的电脑,只留下了必要的东西,但错误仍然存​​在!

为什么当我尝试动态定义变量“buff”时会失败,但是当它被定义为固定大小时(即 Dim buff(0 到 3) as Byte)它工作得很好?

标签: excelvbadynamic

解决方案


下一个代码是否解释了使用方式Redim?它是否也返回错误?

Sub testReadBynReDimArray()
 Dim rec_position As Long, buff() As Byte, rec_len As Long
 rec_len = 5   'choose here what value you need. Even if it will be grater than the whole string, the array will be loaded with 0 bytes for the exceeding elements 
 ReDim buff(0 To rec_len)

 rec_position = 23         '(this is an example)
 Open "C:\MyFile.bin" For Binary Access Read As #1
    Get #1, rec_position, buff
 Close #1

 Debug.Print buff(0), buff(1), buff(2), buff(3), buff(4)
End Sub

推荐阅读