我有一个单元格文字“12-3 0000 9 FLY AIR Make MY Trip
”
我希望像12-3 0000 9
这样的输出到下一个单元格和下一个序列单元格“FLY AIR Make MY Trip
”。
Public Function SplitText(pWorkRng As Range, pIsNumber As Boolean) As String
'Updateby20150306
Dim xLen As Long
Dim xStr As String
xLen = VBA.Len(pWorkRng.Value)
For i = 1 To xLen
xStr = VBA.Mid(pWorkRng.Value, i, 1)
If ((VBA.IsNumeric(xStr) And pIsNumber) Or (Not (VBA.IsNumeric(xStr)) And Not (pIsNumber))) Then
SplitText = SplitText + xStr
End If
Next
End Function
=SplitText(A2,FALSE)
进入空白单元格以获取唯一的文本。
结果为12300009
=SplitText(A2,TRUE)
进入空白单元格以获取唯一的数字。
结果为“ - 飞行空气让我的旅程”
答案 0 :(得分:1)
如果您的参数pIsNumber
设置为true,则假设您想获得数字的第一部分:
Option Explicit
Public Function SplitText(pWorkRng As Range, pIsNumber As Boolean) As String
'Declare ALL variables
Dim xLen As Long
Dim xStr As String
Dim i As Integer
xLen = VBA.Len(pWorkRng.value)
For i = 1 To xLen
xStr = VBA.Mid(pWorkRng.value, i, 1)
If pIsNumber And InStr(" -0123456789", xStr) Then
SplitText = SplitText & xStr ' use ampersand "&" instead of "+"
ElseIf Not pIsNumber And InStr("-123456789", xStr) = 0 Then
SplitText = SplitText & xStr
End If
Next
If pIsNumber Then SplitText = Replace(SplitText, String(3, " "), " ")
End Function
注意强>
使用&符“&”而不是“+”来连接字符串值。顺便说一句,不要忘记声明您的变量,并始终在代码模块的声明头中使用Option Explicit
。
答案 1 :(得分:1)
我会使用Split
,检查文字然后再次加入:
Function SplitText(Txt As String, Optional Number As Boolean = True)
Dim Arr, outarr() As String, I As Integer
Dim nbr As String, rest As String
Arr = Split(Txt, " ")
ReDim outarr(UBound(Arr))
For I = LBound(Arr) To UBound(Arr)
outarr(I) = Arr(I)
If Not IsNumeric(Left(Arr(I), 1)) Then
ReDim Preserve outarr(I - 1)
nbr = Join(outarr, " ")
rest = Mid(Txt, Len(nbr) + 2)
Exit For
End If
Next I
SplitText = IIf(Number, nbr, rest)
End Function
答案 2 :(得分:0)
假设您的文字在单元格A2中
输入以下公式,您需要数字部分(作为数组公式输入,即 CTRL + SHIFT + ENTER 而不仅仅是ENTER):
=LEFT(A2,MIN(IFERROR(SEARCH(CHAR(ROW($A$65:$A$90)),A2,1),2^15))-1)
如果应用正确,Excel将显示周围的大括号{}。
然后假设您在单元格B2中有上面的公式,其结果可以用作输出以获得如下所示的剩余文本部分:
=SUBSTITUTE(A2,B2,"")
如果有效,则不需要VBA。