首页 > 解决方案 > SPLIT 函数:将单元格中的文本转换为数组,但忽略空行

问题描述

有没有办法使用 split 函数填充数组但忽略空行。

我有一本工作簿,里面有成绩单。每个转录本有 1 个单元格,该单元格看起来像这样:

01/04/2019 09:05:18 - Test User 2 (Additional Comments)
Hello


01/04/2019 09:04:43 - Test User 1 (Additional Comments)
Hello

目前我正在使用这段代码:

txt = ActiveCell.Value

FullName = Split(txt, vbLf)

这很好地拆分了单元格文本,但它也包括所有空白行。有没有办法使用拆分功能,然后不要用空行填充数组?

干杯

编辑:

现在使用

txt = ActiveCell.Value
FullName = RemoveBlankLines(Split(txt, vbLf))
For i = UBound(FullName) To 0 Step -1
    Debug.Print FullName(i)
Next i

Function RemoveBlankLines(Strings As Variant) As Variant
    Dim v As Variant
    Dim i As Long, j As Long

    ReDim v(LBound(Strings) To UBound(Strings))
    j = LBound(Strings) - 1
    For i = LBound(Strings) To UBound(Strings)
        If Trim(Strings(i)) <> "" Then
            j = j + 1
            v(j) = Strings(i)
        End If
    Next i

    If j >= LBound(Strings) Then
        ReDim Preserve v(LBound(Strings) To j)
        RemoveBlankLines = v
    End If
End Function

谢谢

标签: arraysexcelvbasplit

解决方案


您可以修复拆分的结果:

Function RemoveBlankLines(Strings As Variant) As Variant
    Dim v As Variant
    Dim i As Long, j As Long

    ReDim v(LBound(Strings) To UBound(Strings))
    j = LBound(Strings) - 1
    For i = LBound(Strings) To UBound(Strings)
        If Trim(Strings(i)) <> "" Then
            j = j + 1
            v(j) = Strings(i)
        End If
    Next i
    If j >= LBound(Strings) Then
        ReDim Preserve v(LBound(Strings) To j)
        RemoveBlankLines = v
    End If
End Function

然后使用

FullName = RemoveBlankLines(Split(txt, vbLf))

推荐阅读