在字符串中搜索数字以确定下一个顺序?

时间:2015-08-05 07:44:10

标签: vba excel-vba dynamic-arrays string-search excel

我有一个内部编号列表(例如R1079-AAA-001,...... 002等),其中“R1079”的值根据所使用的机器而变化。我想要做的是搜索列表以确定与我打算使用的特定机器相关的最后使用的内部版本号(最后3位数)。然后我需要添加一个并为新构建创建一个新日志,即最后一个R1079构建版本为056,因此新版本为057。

目前我所拥有的THEORY是一个字符串搜索机器编号,后跟数字搜索并存储在字符串中并转换为整数。然后将其添加到动态数组中,并在循环完成时找到最大值。一个添加到此整数,新名称放入单元格。

然而,我所拥有的代码不起作用所以我认为我错过了一些东西/弄错了。

以下代码:

Sub test()

Dim x As String
Dim n As Integer
Dim i As Integer
Dim Machine_EBM As String
Dim retval As String
Dim retvalint As Integer
Dim LastBuild As Integer
Dim NextBuild As Integer
Dim myarr() As Integer

Machine = "R1079"

x = Cells("A1").Value 'get the first string in the list
    n = 1
    Do Until x = ""
        If InStr(x, Machine) > 0 Then 'search for machine in string
            For i = 6 To Len(Str) 'search for numbers at end of string
                If Mid(x, i, 1) >= "0" And Mid(x, i, 1) <= "9" Then
                    retval = retval + Mid(s, i, 1) 'store numbers
                End If
            Next i
            retvalint = CInt(retval) ' convert to integer
            ReDim Preserve myarr(n)
            myarr(n) = retvalint ' store integer value in array
            n = n + 1
        End If
    Loop

    LastBuild = Worksheet.Function.Max(myarr(n)) ' determine maximum array value
    NewBuild = LastBuild + 1 'add one to the value

    Range("C1").Select
    ActiveCell = Machine = "-AAA-" + NewBuild 'input new build number

End Sub

我对VBA相当新,并且自学成才,所以我意识到这里可能存在许多我错过的错误。任何帮助表示赞赏!

谢谢,

查理

1 个答案:

答案 0 :(得分:1)

这是一小段代码,用于为输入的构建号获取新构建号。

我已经测试了代码。它给了我正确的答案。所以,你可以使用这段代码。

Public Sub getBuildNo()

    Dim machineCode, lastBuildCode, newBuildCode As String
    Dim buildNo As Integer

    'Set machine code
    machineCode = "R1079"

    'Set last build code
    lastBuildCode = Range("A1")

    'Get last build no
    buildNo = Right(lastBuildCode, 3)

    'Increase 1
    buildNo = buildNo + 1

    'Get new build No
    newBuildCode = machineCode & "-AAA-"

    'adding prefix 0s for getting like (001, 002, 025, etc.)
    If buildNo < 10 Then
        newBuildCode = newBuildCode & "00" & buildNo
    ElseIf buildNo < 100 Then
        newBuildCode = newBuildCode & "0" & buildNo
    Else
        newBuildCode = newBuildCode & buildNo
    End If

    'show new code
    Range("C1") = newBuildCode

End Sub