2012-06-08 19 views
11

Linux'ta oluşturulmuş bir metin dosyam var, eğer Word pad'de açıyorsam dosya normal görünüyor. Ancak notepadde açtığımda ve aşağıdaki kodu kullanarak excel'e yüklemeye çalıştığımda tek satır olarak belirir.VBA kullanarak linux metin dosyasını excel'e yükleme

' 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 

Orijinal hatlara nasıl bölebilirim? Vba'nın kullanabileceği bir satır ayırıcı var mı?

cevap

11

Linux yeni bir satır yerine taşıyıcı dönüşü belirtmek için bir satır besleme (\n) kullanan + satır besleme (\r\n) yerine, Line input kullanamaması için Windows tarafından kullanıldığı gibi:

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

Hat halinde işlem yapmanız gerekiyorsa, 'buff = $ (buff, vbCrLf, vbLf)' _and_ yerine 'split()' mantığını yapın. Bu şekilde, Windows satır sonları Unix stiline normalleştirilir. – kornman00

3

Fonksiyon

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 

ve

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

(immediate window elde edilmiş) ve yukarıdaki Örnek bir metin dosyası kaynaklanan tüm hatları elde etmek için kullanılabilir

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

çıkışı çağırılacak herhangi bir işletim sistemi.


Bu yardımcı olur umarım.

+0

2 yıl sonra bu beni çok çalıştı, çok teşekkür ederim. İşler ters gidinceye kadar bana gelmedi, üzerinde çalıştığım dosyalar bir dizi farklı işletim sisteminden geliyor! Bu bir hayat kurtarıcı. – RossC

İlgili konular