2016-06-22 32 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