VBA拆分限制不按预期工作?

时间:2014-07-14 06:33:07

标签: vba split

所以我试图运行下面的子句,我希望在第二次出现" _"时拆分字符串。但我得到的是一个包含以下元素的数组" 1-SWFEED-4.6.14"," 10"," 3_C"但我想要的是一个包含元素" 1-SWFEED-4.6.14_10"," 3_C"的数组。我做错了什么?

Sub check_split()
Dim iden As String
Dim element As Variant
iden = "1-SWFEED-4.6.14_10_3_C"

For Each element In Split(iden, "_", 3)
    MsgBox element
Next element

End Sub

我也尝试将限制用作UBound(拆分(识别," _")),但它也不起作用。

2 个答案:

答案 0 :(得分:0)

想出了这个我需要的东西(感谢@Maco评论)

Sub check_split()
Dim iden As String
Dim element As Variant
Dim indexCounter As Integer
Dim concIden As String
iden = "1-SWFEED-4.6.14_10_3_C"
indexCounter = 0
For Each element In Split(iden, "_")
    If indexCounter < UBound(Split(iden, "_")) - 1 Then
        If Not indexCounter + 1 = UBound(Split(iden, "_")) - 1 Then
            concIden = concIden + element + "_"
        Else
            concIden = concIden + element
        End If
    End If
    indexCounter = indexCounter + 1
Next element
MsgBox concIden
End Sub

答案 1 :(得分:0)

这个怎么样?

Sub check_split()
    Dim iden As String, splitLocation As Integer, firstPart As String, secondPart As String

    iden = "1-SWFEED-4.6.14_10_3_C"

    splitLocation = WorksheetFunction.Find("_", iden, WorksheetFunction.Find("_", iden, 1) + 1)

    firstPart = VBA.Left$(iden, splitLocation - 1)  //prints 1-SWFEED-4.6.14_10
    secondPart = VBA.Right$(iden, Len(iden) - splitLocation) // prints 3_C
End Sub