VBa写入附加现有文件的二进制文件时出错

时间:2016-08-26 14:43:51

标签: vba excel-vba file binary append

请帮助,这是我的代码,我不知道如何在vba中附加现有文件的另一个元素:

Type TestType
  intVar As Integer
  strVar As String
  predefinedSizeArray(10) As Long
End Type

Public Sub WriteBinary()
   Dim fileName As String, fileNo As Integer, testVar As TestType
   fileName = ThisWorkbook.Path & "\test.bin"

    testVar.intVar = 4
    testVar.strVar = "Hello!"
    testVar.predefinedSizeArray(0) = 15

    fileNo = FreeFile
    Open fileName For Binary Lock Read Write As #fileNo
      Seek #fileNo, LOF(fileNo)
     Put #fileNo, , testVar
    Close #fileNo
End Sub


 Public Sub ReadBinary()
    Dim fileName As String, fileNo As Integer, testVar As TestType
    fileName = ThisWorkbook.Path & "\test.bin"

   fileNo = FreeFile
   Open fileName For Binary Lock Read As #fileNo
   Do While Not EOF(fileNo)
      Get #fileNo, , testVar
      Debug.Print testVar.intVar 'Print the Integer
      Debug.Print testVar.strVar 'Print the String
      Debug.Print testVar.predefinedSizeArray(0) 'Print the String
      Debug.Print TypeName(testVar.predefinedSizeArray)
  Loop
  Close #fileNo
 End Sub

如何做到这一点,如何写入和读取Vba二进制文件而不删除? 请帮忙

2 个答案:

答案 0 :(得分:1)

Append,您需要Seek #fileNo, LOF(fileNo) + 1; + 1移动你超过文件的末尾。

希望有所帮助

答案 1 :(得分:0)

这是另一种编写ReadBinary的方法:

Public Sub ReadBinary()
    Dim fileName As String, fileNo As Integer, testVar As TestType
    fileName = ThisWorkbook.Path & "\test.bin"

    fileNo = FreeFile
    Open fileName For Binary Lock Read As #fileNo
    Do
        Get #fileNo, , testVar
        If EOF(fileNo) Then Exit Do
        Debug.Print testVar.intVar 'Print the Integer
        Debug.Print testVar.strVar 'Print the String
        Debug.Print testVar.predefinedSizeArray(0) 'Print the String
        Debug.Print TypeName(testVar.predefinedSizeArray)
    Loop
    Close #fileNo
End Sub

希望有所帮助。