【问题标题】:VBA-Split doesn't split on space basisVBA-Split 不会在空间基础上拆分
【发布时间】:2019-07-16 07:52:23
【问题描述】:

我是 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 将整行放在一个元素中,而不是按空间拆分。

【问题讨论】:

  • 试试Result() = Split(textline, " ")
  • 试过了,同样的错误
  • 请在解析之前告诉我们textline 持有什么。
  • 我试过了,效果很好。
  • 您的文本不是通过水平制表符分隔吗?我猜你可以试试Split(textline, Chr(9))

标签: excel vba split


【解决方案1】:

更改:

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)

【讨论】:

  • 是的,将其更改为您正确识别的 Char(9)。
  • 是的,更好:)。另请参阅 OP 想要打印元素的方式从 Lbound 到 Ubound 将不起作用。事实上,因为他的数据是制表符分隔的,我猜这是自动数据,他使用它的方式会很好。这只是我的猜测。
  • 无论如何,我认为最好使用Lbound to Ubound,你永远不知道数据什么时候可以有2个Tabs。
  • @Mikki 因此像我的回答一样处理输入。我仍然在那里检查数组的大小。但是,我已将所有 vbTab (Chr(9)) 转换为空格,然后在拆分字符串之前使用 trim 函数删除任何双倍空格。
【解决方案2】:

在使用 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

N.B - 从我的原始答案中删除了vbTab,因为它等同于Chr(9)

【讨论】:

    猜你喜欢
    • 2014-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多