使用VBA将Linux文本文件加载到Excel中

17

我有一个在Linux上创建的文本文件,如果在记事本中打开它,文件看起来正常。但是当我在notepad中打开它,并尝试使用下面的代码将其加载到Excel中时,它看起来像一行。

' Open the file
Open Filename For Input As #1

' Look for the Table Title
Do While Not (EOF(1) Or InStr(TextLine, TableTitle) > 0)
    Line Input #1, TextLine
Loop

我该如何将其分成原始行?有没有换行符可以让vba使用?

3个回答

19

Linux使用换行符(\n)来表示新的一行,而不是Windows所使用的回车符+换行符(\r\n),因此你不能使用Line input,而应该使用:

Open Filename For Input As #1
'//load all
buff = Input$(LOF(1), #1)
Close #1

'//*either* replace all lf -> crlf
buff = replace$(buff, vbLf, vbCrLf)
msgbox buff

'//*or* line by line
dim lines() As String: lines = split(buff, vbLf)
for i = 0 To UBound(lines)
   msgbox lines(i)
next

3
如果你必须逐行处理,你需要这样处理 buff = replace$(buff, vbCrLf, vbLf) ,然后再执行 split() 逻辑。这样可以将 Windows 的换行符规范化为 Unix 样式。 - kornman00

7

这个函数

Public Function GetLines(fpath$) As Variant
    'REFERENCES:
    'Microsoft Scripting Runtime // Scripting.FileSystemObject
    'Microsoft VBScript Regular Expressions 5.5 // VBScript_RegExp_55.RegExp
    Dim fso As New Scripting.FileSystemObject, RE As New VBScript_RegExp_55.RegExp
    If fso.FileExists(fpath) = True Then
        Dim mts As MatchCollection, mt As Match
        Dim lines() As String
        Dim content$: content = fso.OpenTextFile(fpath).ReadAll()
        With RE
            .Global = True
            .Pattern = "[^\r\n]+" 'catch all characters except NewLines/Carraige Returns
            If .test(content) = True Then
                Set mts = .Execute(content)
                ReDim lines(mts.Count - 1)
                Dim pos&
                For Each mt In mts
                    lines(pos) = mt.Value
                    pos = pos + 1
                Next mt
            Else
                MsgBox "'" & Dir(fpath) & "' contains zero bytes!", vbExclamation
            End If
        End With
        GetLines = lines
    Else
        MsgBox "File not found at:" & vbCrLf & Dir(fpath), vbCritical
    End If
End Function

可以通过(从立即窗口)调用

?GetLines("C:\BOOT.INI")(2)

输出结果

default=multi(0)disk(0)rdisk(0)partition(1)\WINDOWS

上述示例可用于获取来自任何操作系统的任何文本文件中的所有行。


希望这有所帮助。


1
两年后,这个工具为我节省了大量的工作,非常感谢。直到出现问题之前,我才意识到我正在处理的文件来自多个不同的操作系统!这真是救命稻草。 - RossC

2

使用Windows的"Word Pad"打开Linux文本文件。保存文件。当保存文件时,Word Pad将把Linux换行符(\n)转换为回车+换行符(\r\n)。不需要编码。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接