2016-06-22 70 views
2

我有一個.txt文件,其中列有|(管道)分隔,但行與以下字符串分隔欄TXT文件:_ ~|~ _VBA有兩個分隔符行和

有沒有辦法通過導入此根據字符串分隔行?如果我能做到這一點,我將能夠輕鬆地將文本寫入列。

這很棘手,因爲記事本中每一行的空間都用盡了。例如:

Policy|Name|Cost _ ~|~ _ 11924|Joe|$20 _ ~|~ _ 154 (end of notepad space) 

35|Bob|$40 _ ~|~ _ 18439|Jane|$30 _ ~|~ _ 18492|Ri 

chard|$50 

我需要這個閱讀:

Policy Name Cost 

11924 Joe $20 

15435 Bob $40 

18439 Jane $30 

18492 Richard $50 

等。請注意,最右邊的值被分割,因爲記事本已經用盡了它的行長。

感謝您的任何想法!

回答

0

使用功能更強大的文本編輯器(如TextPad),可以在導入到Excel之前預處理文本。

在TextPad中,執行替換(F8鍵)。首先讓我們擺脫所謂的「記事本空間的結束」,我將其作爲換行符讀取。

使用正則表達式來沒事取代雙回車 「\ n \ n」:

enter image description here

然後,更換管道 「\ |」用空格「: 」用回車 「\ n」」

enter image description here

然後,替換「 _ ?? _:

enter image description here

這是應該準備最後文本導入到Excel:

enter image description here

希望幫助! TextPad是一個很好的工具。

+1

超讚!謝謝! –

0

您可以使用VBA宏單步執行此操作。

  • 讀入整個文件,以一個VBA字符串變量
  • 上的行刪除newline字符
  • 拆分定界符
    • 這導致一維數組
    • 陣列轉換爲2D陣列
    • 將結果寫入工作表
    • 將文本寫入列■使用豎線作爲分隔符

Option Explicit 
'SET REFERENCE to Microsoft Scripting Runtime 

Sub ImportSpecial() 
    Dim FSO As FileSystemObject 
    Dim TS As TextStream 
    Dim sFN As Variant 
    Dim S As String 
    Dim V As Variant 
    Dim R As Range 

sFN = Application.GetOpenFilename("Text Files (*.txt), *.txt") 
If Not sFN = False Then 
    Set FSO = New FileSystemObject 
    Set TS = FSO.OpenTextFile(sFN, ForReading, False, TristateFalse) 

    'Remove the linefeeds 
    S = TS.ReadAll 
    S = Replace(S, vbNewLine, "") 

    'If data is large, will need to transpose manually 
    V = Application.WorksheetFunction.Transpose(Split(S, "_ ~|~ _")) 

    Set R = ActiveSheet.Cells(1, 1).Resize(UBound(V), 1) 
    With R 
     .EntireColumn.Clear 
     .Value = V 
     .TextToColumns Destination:=R(1), _ 
         DataType:=xlDelimited, _ 
         Tab:=False, semicolon:=False, comma:=False, Space:=False, _ 
         other:=True, otherchar:="|" 
     .EntireColumn.AutoFit 
    End With 
End If 
End Sub