2

我有这个函数,它以字符串形式返回逗号分隔字符串中的值,该字符串按给定整数值的顺序排列。

Private Sub TestGetNthNumber()
    Debug.Print GetNthNumber("NUMBERS 5088, 5089, 5090, 5091", 2)
End Sub

Public Function GetNthNumber(sMark As String, iOrder As Integer) As String
    Dim sTemp As String
    Dim sNumber As String
    Dim iLoop As Integer

    If sMark = "" Then
        Exit Function
    End If

    sTemp = sMark & ","

    For iLoop = 1 To iOrder
        sTemp = Mid(sTemp, InStr(sTemp, " "))
        sNumber = Trim(Left(sTemp, InStr(sTemp, ",") - 1))
        sTemp = Mid(sTemp, InStr(sTemp, ",") + 1)
    Next

    GetNthNumber = sNumber
End Function

测试 Sub 将"5089"作为值列表中的给定数字 2 返回。

我的问题; 有没有更好的方法来做到这一点,而不是使用 Mid、Left 和 InStr 进行凌乱的字符串操作?喜欢将逗号分隔的字符串值转换为数组的方法吗?

另一个问题; 字符串可能是 format"NUMBERS 5088, 5089, 5090 and 5091"。但是为此,我假设在处理它之前" and"替换","

4

2 回答 2

2

另一种选择是使用RegEx/RegExp。您的函数将如下所示:

Public Function GetNthNumberAlternative(sMark As String, iOrder As Integer) As String

    'regexp declaration
    Dim objRegExp As Object
    Set objRegExp = CreateObject("vbscript.regexp")

    With objRegExp
        .Global = True
        .Pattern = "\d+"

        GetNthNumberAlternative = .Execute(sMark)(iOrder - 1).Value 
    End With

End Function

你可以这样称呼它:

Private Sub TestGetNthNumber()
    Debug.Print GetNthNumberAlternative("NUMBERS 5088 AND 5089 OR 5090, 5091", 1)
End Sub
于 2013-07-12T07:03:47.973 回答
1

您想使用该Split功能。如果您每次都有相同的值,那么您可以删除NUMBERS和 final AND。像这样的东西:

Private Sub TestGetNthNumber()
    Debug.Print GetNthNumber("NUMBERS 5088, 5089, 5090, 5091", 2)
End Sub

Public Function GetNthNumber(sMark As String, iOrder As Integer) As String
    Dim vArray As Variant

    sMark = Replace(sMark, "NUMBERS", "")
    sMark = Replace(sMark, "AND", "")
    vArray = Split(sMark, ",")

    GetNthNumber = vArray(iOrder)

End Function
于 2013-07-12T07:01:22.573 回答