在VBA中使用LastIndexOf()拆分字符串

时间:2014-12-11 08:33:32

标签: vba excel-vba excel

如何在VBA中按LastIndexOf()拆分字符串

我有一个可以拥有这些值的字符串

Dim input As String
   input =  "customName_D3"
   input =  "Custom_Name_D3"
   input =  "my_Custom_Name_D3"

就像它可以有很多"_"但是在最后"_"之后它包含了单元格名称 我想拆分此字符串以将单元名称和其他重新生成部分作为两个不同的字符串

之类的东西
cellName = D3
remainingString = my_custom_Name

2 个答案:

答案 0 :(得分:4)

Dim strInput As String
Dim strName As String
Dim strCellAddress As String
Dim iSplit As Integer

strInput = "my_Custom_Name_D3"

iSplit = InStrRev(strInput, "_")

strName = Left(strInput, iSplit - 1)
strCellAddress = Mid(strInput, iSplit + 1)

MsgBox "Name: " & vbTab & strName & vbCrLf & "Cell: " & vbTab & strCellAddress

答案 1 :(得分:0)

请尝试以下代码:

Public Function SplitAtLast(ByVal sText As String, ByVal sMatch As String, ByRef sLeft As String, ByRef sRight As String) As Integer
    Dim nIndex As Integer
    ' Search for sMatch within sText
    nIndex = InStrRev(sText, sMatch)

    If nIndex > 0 Then ' sMatch was found as nIndex'th character
        ' Save all chars before sMatch
        sLeft = Left$(sText, nIndex - 1)
        ' Save all chars after sMatch
        sRight = Mid$(sText, nIndex + Len(sMatch))
    Else ' sMatch was NOT found
        ' Save all chars into sLeft
        sLeft = sText
        sRight = ""
    End If
    ' Returns position of found match
    SplitAtLast = nIndex
End Function

被称为

Dim sInput As String, sLeft As String, sRight As String, nIndex As Integer

sInput = "customName_D3"
nIndex = SplitAtLast(sInput, "_", sLeft, sRight)
MsgBox sInput & " : " & nIndex & ", <" & sLeft & ">, <" & sRight & ">"

sInput = "Custom_Name_D3"
nIndex = SplitAtLast(sInput, "_", sLeft, sRight)
MsgBox sInput & " : " & nIndex & ", <" & sLeft & ">, <" & sRight & ">"

sInput = "my_Custom_Name_D3"
nIndex = SplitAtLast(sInput, "_", sLeft, sRight)
MsgBox sInput & " : " & nIndex & ", <" & sLeft & ">, <" & sRight & ">"

此致 丹尼尔。