二进制访问读取查找特定字符串

时间:2015-02-06 02:23:15

标签: vba find binaryfiles



Sub ReadEntireFileAndPlaceOnWorksheet()
  Dim X As Long, FileNum As Long, TotalFile As String, FileName As String, Result As Variant, Lines() As String
  FileName = "C:\Users\Mohamed samatar.DSSE-EMEA\Documents\EQVL\Test\WHVP113_140910_TTinsug_TT_299Data_PUoff_WOT-TakeOff_NotKickDown_gearD_FelLambda.dat"
  FileNum = FreeFile
  Open FileName For Binary As #FileNum
    TotalFile = Space(LOF(FileNum))
    Get #FileNum, , TotalFile
  Close #FileNum
  Lines = Split(TotalFile, vbNewLine)
  ReDim Result(1 To UBound(Lines) + 1, 1 To 1)
  For X = 1 To UBound(Result)
    Result(X, 1) = Lines(X - 1)
  Next
  Range("A1").Resize(UBound(Result)) = Result
End Sub​




我有一些.dat格式的文件,这些文件包含一些有价值的信息,但它们可能非常大,试图在记事本中打开每个文件并提取我需要的信息根本不高效,因为它需要记事本很长时间打开每个文件。我遇到过这种二进制访问读取功能,它显然可以打开大文件并允许您快速阅读它们。我想知道如何找到/获取特定的信息行,你是否可以使用类似的函数来说出查找功能,或者是否有另一种获取信息的方法,这是我到目前为止所拥有的。它只是告诉我文件类型,本质上我希望能够搜索特定的字符串值,或者如果我可以将所有文本转储到EXCEL中并从那里排序,任何指导都很有用。

1 个答案:

答案 0 :(得分:2)

以下是两个例子。第一行读取文件中的每一行并打印到从单元格A1开始的工作表,然后打印到A2,A3等,每个行一行

Option Explicit
Sub testReadLine()
    Dim filename As String
    Dim FF As Integer
    Dim line As String
    Dim i as Long

    filename = "C:\yourfilename.txt" '### MODIFY AS NEEDED

    FF = FreeFile
    Open filename For Input As FF
    Do While Not EOF(FF)
        Line Input #FF, line

        Range("A1").Offset(i).Value = i
        i = i + 1
    Loop
    Close FF

End Sub

第二个示例将整个文件读入字符串变量,然后使用Split函数将该字符串转换为字符串数组,基于行分隔符(假定为vbCRLF )。

这个应该更快,当然,一旦你在Excel中有数据,你可以使用正常的Excel功能,如“查找”等。

Option Explicit
Option Base 0
Sub testReadAll()

    Dim filename As String
    Dim FF As Integer
    Dim text As String
    Dim buffer As Long
    Dim txtArray() As String

    filename = "C:\yourfilename.txt"  '### MODIFY AS NEEDED

    FF = FreeFile
    Open filename For Input As FF
    buffer = LOF(FF)
    text = Input(buffer, FF)
    Close FF

    'Put the text into an array, split by the LineFeed character:
    txtArray = Split(text, vbCrLf)

    'Print to the worksheet:
    Range("A1").Resize(Ubound(txtArray)).Value = Application.Transpose(txtArray)

End Sub