如何使用Excel VBA从大型txt文件中删除空行?

时间:2018-09-25 17:02:17

标签: excel vba text

我正在尝试使用VBA将大型TXT文件导入到excel文件中。该文件由管道分隔。但是源文件有点混乱,因为有随机的换行符,不能让我正确导入ifles。

COLUMN1|COLUMN2|COLUMN3
DataA1|DataA2|DataTextA3

DataTextA3Continued

DataB1|DataB2|DataTextB3

从技术上讲,DataTextA3DataTextA3Continued之间不应有回车符,但这是我要获取的文件。我该如何在VBA中删除它?我尝试使用vbCrLf进行替换,但是文件很大(20MB),它使excel崩溃了。感谢帮助!

谢谢!

下面的代码。

Sub ReplaceStringInFile()

Dim sBuf As String
Dim sTemp As String
Dim iFileNum As Integer
Dim sFileName As String

' Edit as needed
sFileName = Application.ActiveWorkbook.Path + "\DATAFILE" + Format(Now(), "yyyymmdd") + ".txt"

iFileNum = FreeFile
Open sFileName For Input As iFileNum

Do Until EOF(iFileNum)
    Line Input #iFileNum, sBuf
    sTemp = sTemp & sBuf & vbCrLf
Loop
Close iFileNum

sTemp = Replace(sTemp, vbCrLf, "THAT")

iFileNum = FreeFile
Open sFileName For Output As iFileNum
Print #iFileNum, sTemp
Close iFileNum

End Sub

1 个答案:

答案 0 :(得分:1)

如果多余的换行符总是与最后一列关联,那么我将专注于管道定界符,而不是行。 “记录”将由3个字段组成,因此将整个文件读入缓冲区,然后假定每三个项目都需要替换任何换行符。像这样:

Public Sub ReplaceStringInFile()
    Dim filepath As String
    ' Edit as needed
    filepath = Application.ActiveWorkbook.Path + "\DATAFILE" + Format(Now(), "yyyymmdd") + ".txt"

    Dim handle As Integer
    handle = FreeFile
    Open filepath For Input As #handle
    Dim buffer As String
    'Read the entire file.
    buffer = Input(LOF(handle), handle)
    Close #handle

    handle = FreeFile
    Open filepath For Output As #handle

    Dim lines() As String
    lines = Split(buffer, "|")
    Dim idx As Long
    'This is your output buffer.
    Dim record(0 To 2) As String
    'I'd probably add more bounds checking here, but this should give the gist.
    For idx = LBound(lines) To UBound(lines) - 2 Step 3
        record(0) = lines(idx)
        record(1) = lines(idx + 1)
        'Do your replacement here.
        record(2) = Trim$(Replace$(lines(idx + 2), vbCrLf, " "))
        Print #handle, Join(record, "|")
    Next

    Close #handle
End Sub