使用VBA将linux文本文件加载到excel中

Chr*_*ris 17 linux excel vba excel-vba

我有一个在linux上创建的文本文件,如果我在Word pad中打开它,文件会正常显示.但是当我在记事本中打开它时,当我尝试使用下面的代码将它加载到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
Run Code Online (Sandbox Code Playgroud)

如何将其拆分为原始行?有没有一个行结束分离器,vba可以使用?

Ale*_* K. 15

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
Run Code Online (Sandbox Code Playgroud)

  • 如果你必须进行逐行处理,你想做`buff = replace $(buff,vbCrLf,vbLf)`_和_然后执行`split()`逻辑.这样Windows行结尾标准化为Unix风格. (2认同)

Cyl*_*ian 6

功能

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
Run Code Online (Sandbox Code Playgroud)

并且可以由(来自immediate window)调用

?GetLines("C:\BOOT.INI")(2)
Run Code Online (Sandbox Code Playgroud)

和输出

default=multi(0)disk(0)rdisk(0)partition(1)\WINDOWS
Run Code Online (Sandbox Code Playgroud)

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


希望这可以帮助.