更改VBA宏代码以更改编号

时间:2013-02-20 23:45:31

标签: excel vba

我要做的是增加数字,然后循环减去2前的1个数字 然后增加其余部分,直到第一个2数字= 0

所以我M201001会成为m191002,接下来会是m181003,直到m011020

2 个答案:

答案 0 :(得分:0)

您需要做的是使用leftmidright函数将您的价值分解为3。

然后根据需要进行循环。我正在尝试自己,所以一旦我这样做,我就会更新我的答案。

已添加代码:

Sub Testing()

    Dim myIn As String
    myIn = "M201001"

    Dim myLeft As String
    Dim myMid As Integer, myRight As Integer, i As Integer
    Dim myOut As String
    myLeft = Left(myIn, 1)
    myMid = CInt(Mid(myIn, 2, 2))
    myRight = CInt(Right(myIn, 4))
    myOut = myLeft & Format(myMid, "00") & Format(myRight, "0000")
    i = 0

    Debug.Print "IN:        " & myIn
    Debug.Print "BROKEN UP: " & myOut

    Do Until myMid = -1
        Debug.Print "ITERATION " & Format(i, "00") & ": " & myLeft & Format(myMid, "00") & Format(myRight, "0000")

        myMid = myMid - 1
        myRight = myRight + 1
        myOut = myLeft & Format(myMid, "00") & Format(myRight, "0000")
        i = i + 1
    Loop

End Sub

如果您需要任何解释,请询问。我很乐意解释。

答案 1 :(得分:0)

试试这个

Function GetNextNumber(n As String) As Variant
    ' Validate input
    If Len(n) <> 7 Then
        GetNextNumber = xlErrNum
        Exit Function
    ElseIf Left$(n, 1) <> "M" Then
        GetNextNumber = CVErr(xlErrNum)
        Exit Function
    End If

    GetNextNumber = Left$(n, 1) & Format(val(Mid$(n, 2)) - 9999, "000000")

End Function

使用此

进行测试
Sub demo()
    Dim n As Variant

    n = "M201001"
    Debug.Print n
    Do
        n = GetNextNumber(CStr(n))
        If IsError(n) Then Exit Sub
        Debug.Print n
    Loop Until val(Mid$(n, 2)) <= 19999
End Sub