excel - 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)它工作得很好?
解决方案
下一个代码是否解释了使用方式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
推荐阅读
- javascript - 如何在 Typescript 中使用 oclif fancy-test 存根函数?
- php - 从 URL 获取 JSON 数据并将其存储在数组中,以使用 PHP 中的 foreach 将该数据添加到 mysql
- javascript - 从 OBJECT 数组中删除其他 OBJECT (NPM Twit)
- netlify - 如何向 Netlify 提供 Firebase 管理员凭据?
- ios - 点亮 SpriteKit SKEmitterNode
- linux - Linux 以 root 身份运行 bash 脚本,但在脚本中没有 chmod 权限
- arrays - 将矩阵存储在数组中 - MATLAB
- c# - 格式化int值时如何处理前导零
- laravel - Laravel 护照:安装错误:不创建 oauth 公钥和私钥
- c# - Blazor Server 如何跨多个选项卡和刷新保存数据