2012-06-08 28 views
11

Tengo un archivo de texto creado en Linux, si lo abro en Word pad el archivo aparece normalmente. Sin embargo, cuando lo abro en el bloc de notas, y cuando intento cargarlo en Excel utilizando el siguiente código, aparece como una sola línea.Cargando el archivo de texto de Linux en excel usando VBA

' 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 

¿Cómo puedo dividirlo en las líneas originales? ¿Hay un separador de final de línea, que vba puede usar?

Respuesta

11

Linux utiliza un de avance de línea (\n) para denotar una nueva línea en lugar del retorno de carro + de avance de línea (\r\n) y usadas por Windows, por lo que no se puede utilizar Line input, en su lugar:

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 
+0

Si tiene que hacer el procesamiento línea por línea, quiere hacer 'buff = replace $ (buff, vbCrLf, vbLf)' _and_ luego hacer la lógica 'split()'. De esta manera, las terminaciones de línea de Windows se normalizan al estilo Unix. – kornman00

3

La Función

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 

y podrían ser invocados (de immediate window)

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

y la salida

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

El ejemplo anterior podría ser utilizado para obtener todas las líneas de cualquier archivo de texto se originó a partir cualquier sistema operativo.


Espero que esto ayude.

+0

2 años después y esto me ha ahorrado MUCHO trabajo, muchas gracias. ¡No se me ocurrió hasta que las cosas salieron mal, que los archivos en los que estoy trabajando provienen de varios sistemas operativos diferentes! Este es un salvavidas. – RossC