Reading first few characters in large text files in VBA

浪尽此生 提交于 2020-01-05 05:47:10

问题


I'm trying to read the first few characters in large (>15MB) files in excel. Right now, I'm using the typical:

Set MyObject = New Scripting.FileSystemObject
Set mySource = MyObject.GetFolder(mySourcePath)
For Each myFile In mySource.Files
    With New Scripting.FileSystemObject
        With .OpenTextFile(myFile, ForReading)
            test_str = .ReadLine
            'Do things
        End With
    End With
Next

The issue is with large files, I (believe) you're loading into memory the WHOLE thing only to read the first few characters. Is there a way to just extract the first 6 characters?


回答1:


An alternative to the FileSystemObject would be ADO

However, your statement

I (believe) you're loading into memory the WHOLE thing only to read the first few characters.

is wrong.

What I think is misleading you is the fact that you are not exiting the loop after you read the first line. You get what you want by reading line by line but you are not closing the file right away. It's a good programmers practice to always close any objects you initiate in your code. Don't just leave it hanging and don't rely on the environment to kill them.

Consider the below code as an alternative to yours and see if there is any efficiency difference

Option Explicit

' add references to Microsoft Scripting Runtime
' Tools >> References >> Microsoft Scripting Runtime
Sub Main()

    Dim fileName As String
    ' make sure to update your path
    fileName = "C:\Users\FoohBooh\Desktop\Project.txt"

    ReadTxtFile fileName


End Sub

Sub ReadTxtFile(fileName)

    Dim oFSO As New FileSystemObject
    Dim oFS As TextStream

    Set oFS = oFSO.OpenTextFile(fileName)

    Dim content As String
    content = oFS.ReadLine

    With Sheets(1).Range("A1")
        .ClearContents
        .NumberFormat = "@"
        .Value = content
    End With

    oFS.Close
    Set oFS = Nothing

End Sub

The above code reads the first line of a .txt file into cell A1 of the first sheet. Remember to set a fileName variable to a full path.



来源:https://stackoverflow.com/questions/18594258/reading-first-few-characters-in-large-text-files-in-vba

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!