VBA – Txt文件带有两个行和列的分隔符
我有一个.txt
文件,其中列用|
分隔 (pipe道),但行使用以下string分隔: _ ~|~ _
有没有办法通过基于string分隔行来导入? 如果我能做到这一点,我可以很容易地做文本到列。
这是非常棘手的,因为记事本中每一行的空间都被耗尽了。 例如:
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
等等。 请注意,最右边的值被拆分,因为记事本已经用尽了它的行长。
感谢您的任何想法!
使用function更强大的文本编辑器(如TextPad),可以在导入Excel之前预处理文本。
在TextPad中,执行replace(F8键)。 首先让我们摆脱你所谓的“记事本空间的结束”,我把它看作是换行符。
使用正则expression式来replace双重回车符“\ n \ n”
然后,replacepipe道“\ |” 与空格“”:
然后,用回车符“\ n”replace“_〜〜_”:
这是准备导入Excel的最终文本:
希望有所帮助! TextPad是一个很好的工具。
您可以使用VBAmacros单步执行此操作。
- 将整个文件读入一个VBAstringvariables
- 删除
newline
- 拆分行分隔符
- 这导致了一维数组
- 将数组转换为二维数组
- 将结果写入工作表
- 使用pipe道作为分隔符将文本显示到列
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