我认为这个功能可能是过度杀戮。但它会做你想做的事。
Function SplitCellValue(ByVal CellVal As String) As String
'137
Const Qualifiers As String = "tenant,resident"
Dim Fun() As String ' function return array
Dim n As Integer ' index of Fun()
Dim Qword() As String ' split Qualifiers
Dim q As Integer ' index of Qword
Dim Sp() As String ' split array
Dim i As Integer ' index of Sp()
Dim Skip As Boolean ' True if entry doesn't qualify
Dim Append As Boolean ' True to append unqualified entry to previous
If Len(CellVal) Then ' skip blank CellVal
Qword = Split(Qualifiers, ",")
Sp = Split(Trim(CellVal), ",")
ReDim Fun(1 To UBound(Sp) + 1)
For i = 0 To UBound(Sp)
If InStr(Sp(i), ":") Then
For q = LBound(Qword) To UBound(Qword)
Skip = CBool(InStr(1, Sp(i), Qword(q), vbTextCompare))
If Skip Then Exit For
Next q
If Skip Then
n = n + 1
Fun(n) = Trim(Sp(i))
Append = True
Else
Append = False
End If
Else
If n = 0 Then
' preserve unqualified, leading entry
n = 1
Append = True
End If
If Append Then
If Len(Fun(n)) Then Fun(n) = Fun(n) & ", "
Fun(n) = Fun(n) & Trim(Sp(i))
End If
End If
Next i
End If
If i Then
ReDim Preserve Fun(1 To n)
SplitCellValue = Join(Fun, ", ")
End If
End Function
列出常量Qualifiers 中的所有限定符。其他一切都将被拒绝。限定符仅在与冒号出现在相同的逗号分隔元素中时才限定元素。 (我可能还不如将两者结合起来,但我没有。)
您可以在 VBA 中通过这样的调用使用此函数。
Private Sub Test_SplitCellValue()
Dim R As Integer
For R = 2 To 5
Debug.Print i, SplitCellValue(Cells(R, 1).Value)
Next R
End Sub
或作为 UDF,称为 =SplitCellValue(A2)。为此使用安装在标准代码模块中。
过度杀戮是函数可以做的事情可能不需要。 (1) 空白单元格将返回空白。 (2) 非空白单元格如果没有找到冒号,则返回其原始值。 (3) 第一个元素之前带有冒号的任何内容都将包含在返回中。 (4) 删除原文中的空格并用逗号后面的空格替换,这些空格本身也被删除,然后放置在限定元素之间。所有这些都需要大量代码,如果您的数据或期望与我的预期不一致,则可能需要修改这些代码。