VBA-Split不按空间分割

时间:2019-07-16 07:52:23

标签: excel vba split

我是VBA的新手。我将解析以下格式的文本文件:

040 11  VAR1    TRUE
040 12  VAR2    FALSE
040 13  VAR3    FALSE
040 14  VAR4    FALSE

我使用了代码:

Sub Bouton4_Cliquer()

Dim myFile As String, text As String, textline As String

myFile = "C:\Users\Andrea\Desktop\textlist.txt"
Open myFile For Input As #1

Dim Result() As String
Dim i As Integer

i = 1
Do Until EOF(1)
    i = i + 1
    Line Input #1, textline
    Result() = Split(textline)

    Worksheets("BOOLEAN").Cells(i, 1).value = Result(2)
    Worksheets("BOOLEAN").Cells(i, 2).value = Result(1)
    Worksheets("BOOLEAN").Cells(i, 3).value = Result(0)
    Worksheets("BOOLEAN").Cells(i, 4).value = Result(3)
Loop

Close #1
End Sub

由于Result()仅包含一个元素,这会向我返回错误。

事实上,我注意到Split将整行放在一个元素中,而没有基于空间进行拆分。

2 个答案:

答案 0 :(得分:2)

更改:

Result() = Split(textline)

使用方式:

Result() = Split(textline, Chr(9))' Tab or any other character that you want to use as delimiter 

Split将另一个参数作为分割依据。

还请注意,如果您的数据在两个单词之间有一个以上的空格,那么您打印数据的方式将不会打印所有的元素。我建议你用 Lbound(Result) to Ubound(Result)

答案 1 :(得分:0)

在使用Split功能之前,请尝试清理输入内容。下面将用空格替换所有制表符,并删除所有双倍或更多的空格

Sub Bouton4_Cliquer()
    Dim myFile As String, text As String, textline As String

    myFile = "C:\Users\Andrea\Desktop\textlist.txt"
    Open myFile For Input As #1

    Dim Result() As String
    Dim i As Long

    i = 1
    Do Until EOF(1)
        i = i + 1
        Line Input #1, textline

        ' This will remove any tabbed characters and replace with spaces and remove any non-single spacing between words
        textline = WorksheetFunction.Trim(Replace(textline, Chr(9), " "))

        Result() = Split(textline)

        ' Test if array is correct size, if not print to Immediate Window
        If UBound(Result) - LBound(Result) + 1 <> 4 Then Debug.Print "Error with line:", Join(textline, ";")

        Worksheets("BOOLEAN").Cells(i, 1).Value = Result(2)
        Worksheets("BOOLEAN").Cells(i, 2).Value = Result(1)
        Worksheets("BOOLEAN").Cells(i, 3).Value = Result(0)
        Worksheets("BOOLEAN").Cells(i, 4).Value = Result(3)
    Loop

    Close #1
End Sub

NB-从我的原始答案中删除了vbTab,因为它等效于Chr(9)