Excel VBA 读取Binary 档并填入储存格中

使用情境如下图,按下Loaf File 按钮之后,依C4内的档案路径读取bin档,并分段填入C1及C2中
http://img2.58codes.com/2024/201610521002lSqW2k.png

先上程式

1  Sub Load_File()2 3     Dim FilePath As String4    5     FilePath = Replace(Range("C4").Value, """", "")6    7     'Debug.Print FilePath8    9     Dim FileLen As Integer10    Dim str As String11    12    Dim byteArr() As Byte13    Dim fileInt As Integer: fileInt = FreeFile14    15    Open FilePath For Binary Access Read As #fileInt16    FileLen = LOF(fileInt) - 117    ReDim byteArr(0 To FileLen)18    Get #fileInt, , byteArr19    Close #fileInt20    21    str = ""22    For i = 0 To 819123        If byteArr(i) < 16 Then24            str = str + "0" + Hex(byteArr(i)) + " "25        Else26            str = str + Hex(byteArr(i)) + " "27        End If28        29    Next30    Range("C1").Value = str31    32    'Debug.Print str33    'Debug.Print "========================================="34    35    str = ""36    For i = 8192 To FileLen37        If byteArr(i) < 15 Then38            str = str + "0" + Hex(byteArr(i)) + " "39        Else40            str = str + Hex(byteArr(i)) + " "41        End If42  Next43   Range("C2").Value = str44   45   'Debug.Print str46 End Sub

读取档案的部份参考 how can I read a binary file using VBA?再做修改,以下几个坑说明一下:
1.要分段是因为Excel一个储存格能放的字数有限,所以才需要方两段分别放到不同储存格
2. 将路径读进来时双引号「"」要去掉,用Replace函数可将双引号取代掉,而表示双引号字元的方法为「""""」四个双引号,也就是在双引号中间要以两个双引号来代表一个双引号 (有够绕口XD
3. 读出来的档案放在byteArr中,为16进位数值,用HEX()函数即可转换为16进位字串
4. 24~26行是补0的判断,让转出来的数值保持为两位数,以及在每一个数值后面加空格


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章