Function extract(word As String, Optional separator As String = "_", Optional ByVal index As Long = -2)
' index = 1 gives first word, 2 gives 2nd word...
' index -1 gives last word, -2 gives 2nd last word...
Dim tokens() As String
tokens = Split(word, separator)
If index < 0 Then index = UBound(tokens) + index + 1 Else index = index - 1
If index >= 0 And index <= UBound(tokens) Then extract = tokens(index)
End Function
Function SPLITTEXT(s As String, del As String, Optional indx As Long = 1) As String
If indx < 0 Then
s = StrReverse(s)
SPLITTEXT = StrReverse(Split(s, del)(Abs(indx) - 1))
Else
SPLITTEXT = Split(s, del)(Application.Max(indx, 1)- 1)
End If
End Function
或者,也许:
Function SPLITTEXT(s As String, del As String, Optional indx As Long = 1) As String
Dim r As Variant: r = Split(s, del)
If indx < 0 Then
SPLITTEXT = r(UBound(r) + indx - 1)
Else
SPLITTEXT = r(Application.Max(indx, 1) - 1)
End If
End Function
Dim sMyString As String
Dim Pos1 As Long
Dim Pos2 As Long
Dim Result As String
sMyString = "88/12_PO/SP_SJ_#448491_WHITE_10A_60"
Pos1 = InStrRev(sMyString, "_")
Pos2 = InStrRev(sMyString, "_", Pos1 - 1)
Result = Mid(sMyString, Pos2 + 1, Pos1 - 1 - Pos2) 'this will return 10A
你也可以把它放在一个函数中
Public Function ExtractString(sMyString As String) As String
Dim Pos1 As Long
Dim Pos2 As Long
Dim Result As String
Pos1 = InStrRev(sMyString, "_")
Pos2 = InStrRev(sMyString, "_", Pos1 - 1)
ExtractString = Mid(sMyString, Pos2 + 1, Pos1 - 1 - Pos2)
End Function
4条答案
按热度按时间tuwxkamq1#
*2
是从右侧开始的计数,因此它将返回从右侧开始的第二个计数。将它更改为*3
将返回从右侧开始的第三个计数(在您的示例中为白色):uxh89sit2#
标记VBA时:这可以是要使用的UDF。
缺省分隔符为“_",但您可以指定任何其他分隔符
默认的棋子是倒数第二个(index = -2),但是你可以要求任何其他的位置
只需在Excel中使用类似
=Extract(B2)
的公式tzdcorbm3#
让我给你一些建议:
这不是我的强项,但我会在这里使用
Split()
选项:或者,也许:
调用类似
=SPLITTEXT(A1,"_",-2)
的函数,我尝试模仿TEXTBEFORE()
的第3个参数,让您从左 * 或 * 右选取索引。或者:
elcex8rz4#
如果您需要分多个步骤执行,则可以这样做:
你也可以把它放在一个函数中