从右侧提取Excel中第二个下划线后的文本

vlurs2pr  于 2023-02-05  发布在  其他
关注(0)|答案(4)|浏览(530)

需要从单元格中的字符串提取第一个和第二个“_”之间的文本。
示例-88/12_PO/SP_SJ_#448491_WHITE_10A_60
需要从上述字符串中提取“10A”

=MID(B2, SEARCH("_",B2) + 1, SEARCH("_",B2,SEARCH("_",B2)+1) - SEARCH("_",B2) - 1)
tuwxkamq

tuwxkamq1#

*2是从右侧开始的计数,因此它将返回从右侧开始的第二个计数。将它更改为*3将返回从右侧开始的第三个计数(在您的示例中为白色):

=TRIM(LEFT(RIGHT(SUBSTITUTE(B2,"_",REPT(" ",LEN(B2))),LEN(B2)*2),LEN(B2)))
uxh89sit

uxh89sit2#

标记VBA时:这可以是要使用的UDF。
缺省分隔符为“_",但您可以指定任何其他分隔符
默认的棋子是倒数第二个(index = -2),但是你可以要求任何其他的位置

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

只需在Excel中使用类似=Extract(B2)的公式

tzdcorbm

tzdcorbm3#

让我给你一些建议:

    • VBA:**

这不是我的强项,但我会在这里使用Split()选项:

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

调用类似=SPLITTEXT(A1,"_",-2)的函数,我尝试模仿TEXTBEFORE()的第3个参数,让您从左 * 或 * 右选取索引。

    • 电子表格ms365**:
=@TAKE(TEXTSPLIT(A1,"_"),,-2)
    • 适用于Windows的Excel 2013及更高版本**:
=FILTERXML("<t><s>"&SUBSTITUTE(A1,"_","</s><s>")&"</s></t>","//s[last()]/preceding::*[1]")

或者:

=FILTERXML("<t><s>"&SUBSTITUTE(A1,"_","</s><s>")&"</s></t>","//s[position() = last()-1]")
elcex8rz

elcex8rz4#

如果您需要分多个步骤执行,则可以这样做:

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

相关问题