[英]Excel VBA - how to find the next largest substring value
I have a single column range of values as part of a table. 我有一个值的单列范围作为表的一部分。 The values in this column are groups of sequential strings such as:
此列中的值是顺序字符串的组,例如:
ABC-001
ABC-002
XYZ-001
EFDDGE-001
ABC-003
XYZ-002
ABC-004
What I need to do is assign a value in the next row that is the next value in the whatever the group is. 我需要做的是在下一行中分配一个值,该值即为该组中的下一个值。
Example: 例:
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.
You could use a formula like this 您可以使用这样的公式
=LEFT(A1,FIND("-",A1)-1)&"-"&RIGHT("00"&RIGHT(A1,LEN(A1)-FIND("-",A1))+1,3)
This will, however, only work as long as the number indexation is restricted to 3 digits. 但是,这仅在数字索引限制为3位数字的情况下才有效。
Here is a little sub I threw together to hopefully get you pointed in the right direction. 我汇总了以下内容,希望能使您指出正确的方向。 There are a lot of improvements that could be made to the following code but it is functional.
以下代码可以进行很多改进,但是它们是有效的。 I am assuming that you know how to add and run subroutines.
我假设您知道如何添加和运行子例程。 If you need any clarification please let me know.
如果您需要任何澄清,请告诉我。
image: sample data and output 图片: 样本数据和输出
code: 码:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.