字符串不匹配

时间:2018-10-27 15:49:19

标签: excel vba string excel-vba

具有下一个文本:“ CLS(C218)4门轿跑车10-16,具有固定点”。 我必须将起始年(10)和结束年(16)作为字符串保存在变量中。问题是,当我运行下一个代码时:

StartYr = Split(Years, "-")(0)

EndYr = Split(Years, "-")(1)

StartYr将为“点”,而EndYr将为空。 如何更改StartYr为“ 10”而EndYr为“ 10”?

4 个答案:

答案 0 :(得分:1)

考虑:

Sub getYears()
    Dim s As String, arr, arr2, a

    s = "CLS (C218) 4 doors Coupe 10-16 with fixed points"

    arr = Split(s, " ")
    For Each a In arr
        If InStr(a, "-") > 0 Then
            arr2 = Split(a, "-")
            MsgBox arr2(0) & vbCrLf & arr2(1)
            Exit Sub
        End If
    Next a
End Sub

enter image description here

答案 1 :(得分:1)

如果StartYrEndYr始终是两位数字:

StartYr = Right(Split(Years, "-")(0), 2)
EndYr = Left(Split(Years, "-")(1), 2)

答案 2 :(得分:1)

您也可以使用instr和mid这些方法...在这种情况下,结果将为您提供两个长度为10和16的数字。

Sub test()
Dim pos As Integer
Dim s, s1, s2 As String

 s = "CLS (C218) 4 doors Coupehhhh 10-16 with fixed points"
pos = InStr(1, s, "-") ' get position of "-"
s1 = Mid(s, pos - 2, 2) 'get 10. find position "-"  come back of two position and take 2 chars
s2 = Mid(s, pos + 1, 2) 'get 16. find position "-" come ahead 1 position and take two chars
End Sub

答案 3 :(得分:0)

您也可以这样做。

Sub test()
    Dim vS, s1, s2
    Dim s  As String
    Dim StartYr As Integer
    Dim EndYr As Integer

    s = "CLS (C218) 4 doors Coupe 10-16 with fixed points"

    vS = Split(s, "-")
    s1 = Split(vS(0))
    s2 = Split(vS(1))

    StartYr = Trim(s1(UBound(s1)))
    EndYr = Trim(s2(LBound(s2)))
    MsgBox StartYr & vbCrLf & EndYr

End Sub