如何确定字符串中的字符串包括所有数字

时间:2019-01-17 16:26:15

标签: arrays vba string

我有一个字符串,应该是单词代码。它包括两个字母,后跟一个数字。

我正在尝试确定该字符串中都包含哪些单词代码组合。我通过将每个单词/数字放在一个数组中来分离字母,但是我被困在如何知道例如16-28是否表示16到28之间的所有数字。

这是我的代码:

Dim arrayString() As String
arrayString = Split("MH12, MH13, MH16-28").Value, ",")
For i = 0 To UBound(arrayString)
    msgString = arrayString(i) & vbCr
Next i

我需要确定的输出应该是:

MH12, MH13, MH16, MH17, MH18, MH19, MH20, MH21, MH22, MH23, MH24, MH25, MH26, MH27, MH28

1 个答案:

答案 0 :(得分:3)

这是一个您可能会发现有用的功能:

Function ExpandString(str As String, Optional delim As String = ",") As String
    Dim terms As Variant
    Dim i As Long, j As Long, m As Long, n As Long
    Dim term As String, result As String, numstr As String

    terms = Split(str, delim)
    For i = 0 To UBound(terms)
        term = Trim(terms(i))
        If Not term Like "*-*" Then
            result = result & delim & term
        Else
            numstr = Mid(term, 3)
            m = Split(numstr, "-")(0)
            n = Split(numstr, "-")(1)
            For j = m To n
                result = result & delim & Left(term, 2) & j
            Next j
        End If
    Next i
    If Len(result) >= 2 Then result = Mid(result, 1 + Len(delim))
    ExpandString = result
End Function

例如,在立即窗口中:

?ExpandString("MH12, MH13, MH16-28")
MH12,MH13,MH16,MH17,MH18,MH19,MH20,MH21,MH22,MH23,MH24,MH25,MH26,MH27,MH28

还有(注意逗号后的空格):

?expandstring("MH12, MH13, MH16-28", ", ")
MH12, MH13, MH16, MH17, MH18, MH19, MH20, MH21, MH22, MH23, MH24, MH25, MH26, MH27, MH28