Scripting.FileSystemObject在Write方法上耗尽内存

时间:2015-08-14 19:18:55

标签: excel vba

我正在使用此代码将字符串写入TXT文件。

它适用于文件< 40mbs但是我试图保存的TXT会有点大~45mb并且当我到达.write行时我收到错误“Out of memory”。

Private Sub SaveToTXT(FilePath As String, FileContents As String)
    Dim fso As Object
    Dim oFile As Object
    FileManagementFactory.DeleteIfExists (FilePath)
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set oFile = fso.CreateTextFile(FilePath)
    Call oFile.Write(FileContents)
    Call oFile.Close
    Set fso = Nothing
    Set oFile = Nothing
End Sub

知道如何绕过这个问题吗?

2 个答案:

答案 0 :(得分:0)

在这里,试试这个。

Private Sub SaveToTXT(FilePath As String, FileContents As String)
    Dim nFileNum As Integer: nFileNum = FreeFile
    Open FilePath For Binary Lock Read Write As #nFileNum
    Put #nFileNum, , FileContents
    Close #nFileNum
End Sub

答案 1 :(得分:0)

这是我最终做的,它将文件分成20,000,000个字符串。在我的测试中,它似乎超过了内存限制。

Private Sub SaveToTXT(FilePath As String, FileContents As String)
    Dim fso As Object
    Dim oFile As Object
    Dim l As Long
    Dim CharactersPerChunk As Long
    CharactersPerChunk = 20000000
    FileManagementFactory.DeleteIfExists (FilePath)
    Set fso = CreateObject("Scripting.FileSystemObject") ' A lot faster than ADODB.Stream
    Set oFile = fso.CreateTextFile(FilePath)
    l = 0
    While l < Len(FileContents) / CharactersPerChunk
        Call oFile.Write(Mid(FileContents, (l * CharactersPerChunk) + 1, CharactersPerChunk))
        l = l + 1
    Wend
    Call oFile.Close
    Set fso = Nothing
    Set oFile = Nothing
End Sub