Excel VBA - 如何查找下一个最大的子字符串值

时间:2015-12-18 13:04:56

标签: excel-vba vba excel

我将一列值作为表的一部分。此列中的值是连续字符串组,例如:

ABC-001
ABC-002
XYZ-001
EFDDGE-001
ABC-003
XYZ-002
ABC-004

我需要做的是在下一行中分配一个值,该值是该组中的下一个值。

示例:

If the next item is an "ABC" item, I need the value in the column to be ABC-005
If the next item is a "EFDDGE" item, I need the value in the column to be EFDDGE-002 etc.

2 个答案:

答案 0 :(得分:1)

你可以使用这样的公式

=LEFT(A1,FIND("-",A1)-1)&"-"&RIGHT("00"&RIGHT(A1,LEN(A1)-FIND("-",A1))+1,3)

但是,只有数字索引限制为3位数时才会起作用。

答案 1 :(得分:0)

这是一个小小的我扔在一起,希望能让你指向正确的方向。可以对以下代码进行许多改进,但它是有效的。我假设你知道如何添加和运行子程序。如果您需要任何澄清,请告诉我。

图像: sample data and output

代码:

Option Explicit

' This sub will get generate the next integer value for all of the unique prefixes provided in column A
'   desired input format is xxxx-xxxx
Sub getNextValue()

    Dim lastRow As Long

    With Sheets("Sheet1")
        lastRow = .Range("A" & .Rows.Count).End(xlUp).Row
    End With

    Dim arrayPrefix() As String
    Dim arrayMax() As String
    Dim i As Integer
    Dim iData As String
    Dim prefixData As String
    Dim maxData As String
    Dim test As String
    Dim index As String

    ReDim arrayPrefix(0)
    ReDim arrayMax(0)

    For i = 1 To lastRow

        iData = Cells(i, 1).Value
        prefixData = Split(iData, "-")(0)
        maxData = Split(iData, "-")(1)

        If CheckInArray(prefixData, arrayPrefix) Then

            index = Application.Match(prefixData, arrayPrefix, False) - 1

            ' keeps the maximum value encountered so far
            If maxData > arrayMax(index) Then

                arrayMax(index) = maxData

            End If


        Else

            ' resizes the matricies to hold more if needed.
            ReDim Preserve arrayPrefix(UBound(arrayPrefix) + 1)
            ReDim Preserve arrayMax(UBound(arrayMax) + 1)
            arrayPrefix(UBound(arrayPrefix)) = prefixData
            arrayMax(UBound(arrayMax)) = maxData

        End If

    Next i


    ' Output next values to adjacent columns
    For i = 1 To UBound(arrayPrefix)

        Cells(i, 3).Value = arrayPrefix(i)
        Cells(i, 4).Value = arrayMax(i) + 1

    Next i


End Sub


Function CheckInArray(stringToBeFound As String, arr As Variant) As Boolean

    Dim i As Integer

    For i = 0 To UBound(arr)

        If arr(i) = stringToBeFound Then

            CheckInArray = True
            Exit Function

        End If


    Next i

  CheckInArray = False

End Function