VBA-二进制文件的读取(仅限小文件)

Sub 二进制读取()
    Dim filename As String
     filename = ThisWorkbook.path & "\text.txt"
     Open filename For Binary As #1 '打开文件,可以对文件进行读写操作
     Dim chs() As Byte, i As Integer, k As Integer
     For i = 0 To LOF(1) - 1 '循环至文件末端
     k = k + 1
     ReDim chs(1 To k) As Byte '将文件内容存入字节数组
     Get #1, , chs(k) '获取文本内容
     Next i
     Close #1
     MsgBox chs
    
 End Sub1.将文件的数据读取出来,其代码和解释如下

2.二进制文件的写入

Sub 写入二进制文件()
     Dim filename As String
     filename = ThisWorkbook.path & "\text.txt"
     Open filename For Binary As #1
   
    Dim s As String
    s = "今天天气真好"
    Put #1, , s '将内容写入文件
    Close #1
   
 
 End Sub

3.二进制文件的复制

Sub 复制文件() '将#1的文件内容复制到#2
    Dim filename As String, filetarget As String
    filename = ThisWorkbook.path & "\text.txt"
    filetarget = ThisWorkbook.path & "\sdd.txt"
    Open filename For Binary As #1
    Open filetarget For Binary As #2
    Dim i As Integer, ch As Byte
    For i = 0 To LOF(1) - 1
        Get #1, , ch
        Put #2, , ch
    Next i
    Close #1, #2
 End Sub


猜你喜欢

转载自blog.csdn.net/qq_41777527/article/details/81050455