【问题标题】:SPLIT Function: Text from a cell into an array but ignore the blank linesSPLIT 函数:将单元格中的文本转换为数组,但忽略空行
【发布时间】:2019-09-28 09:47:54
【问题描述】:

有没有办法使用 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

谢谢

【问题讨论】:

    标签: arrays excel vba split


    【解决方案1】:

    您可以修复拆分的结果:

    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))
    

    【讨论】:

      【解决方案2】:

      您始终可以将两个背靠背换行符替换为一个:

      txt = Replace(txt, vbLf, "|")
      txt = Replace(txt, "||", "|")
      txt = Replace(txt, "||", "|")
      txt = Replace(txt, "||", "|")
      
      FullName = Split(txt, "|")
      

      【讨论】:

        【解决方案3】:

        简而言之,其他答案之一,您也可以这样做:

        Split(Replace(txt, vbLf + vbLf, ""), vbLf)
        

        【讨论】:

          【解决方案4】:

          另一个,只是为了好玩:

          txt = Split(Replace(Join(Filter(Split("~" & Replace(ActiveCell.Value, vbLf, "~|~") & "~", "|"), "~~", False), vbLf), "~", ""), vbLf)
          

          【讨论】:

          • 简直是疯了
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2013-06-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-03-12
          • 2017-11-07
          相关资源
          最近更新 更多