有没有一种方法可以使用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
谢谢
答案 0 :(得分:3)
您可以修复拆分结果:
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))
答案 1 :(得分:2)
您始终可以将两个换行符替换为一个:
txt = Replace(txt, vbLf, "|")
txt = Replace(txt, "||", "|")
txt = Replace(txt, "||", "|")
txt = Replace(txt, "||", "|")
FullName = Split(txt, "|")
答案 2 :(得分:1)
简而言之,您还可以这样做:
Split(Replace(txt, vbLf + vbLf, ""), vbLf)
答案 3 :(得分:1)
另一种,只是为了好玩:
txt = Split(Replace(Join(Filter(Split("~" & Replace(ActiveCell.Value, vbLf, "~|~") & "~", "|"), "~~", False), vbLf), "~", ""), vbLf)