如何设置我的Do ... While ... Loop(VBA)的延续?

时间:2014-03-12 14:08:11

标签: string vba loops concatenation

现在,我只是显示一个显示文件名的消息框(例如这里是PrettyPonies),一个连字符,以及一个从001,002,003开始的后缀......等等。推荐用于后缀的方法很有效,直到它击中" 010"此时它会显示" 0010"因为它的设置方式。为了解决这个问题,我想创建两组Do ... While循环如下:

Sub IntegerTestforSuffixFinder()

Dim i As Double
Dim NameStr As String
Dim LengthMeasure As Integer

NameStr = "PrettyPonies"
LengthMeasure = Len(NameStr)

    Do While i < 9
    i = i + 1
        If vbOK Then
   '3-character string created by using the Right() function
   MsgBox Right(NameStr + "-" + "00" & i, LengthMeasure + 4)
        Else: End
        End If

    Do While i > 10 And i < 99
    i = i + 1
        If vbOK Then
    MsgBox Right(NameStr + "-" + "0" & i, LengthMeasure + 4)
        Else: End
        End If

Loop
Loop

End Sub

但是,我知道我在循环之间遗漏了一些东西,使其继续到第二组。我试过让它成为一个完全不同的子,并尝试说继续或然后无济于事。该程序在击中009后退出该子程序。

如何组合我的循环以使其最多可计数99?

3 个答案:

答案 0 :(得分:3)

单循环使用此代码:

Sub IntegerTestforSuffixFinder()

    Dim i As Double
    Dim NameStr As String
    Dim LengthMeasure As Integer

    NameStr = "PrettyPonies"
    LengthMeasure = Len(NameStr)

    Do While i < 99
        i = i + 1
        If vbOK Then
            '3-character string created by using the Right() function
            MsgBox NameStr & "-" & Right("00" & i, 3)
        Else: Exit Sub
        End If
    Loop
End Sub

顺便说一下,请勿使用Else: End,而是使用Else: Exit Sub

还有一件事,因为vbOK等于1,您的Else部分永远不会评估。在您的真实代码中,您可以使用以下内容:

If MsgBox("Any Question", vbOKCancel) = vbOK Then

答案 1 :(得分:1)

你跳过10,因为你在i时的测试时间大于10.另外,你从不会从9增加到10.要修复当前的实现,请试试这个:

Sub IntegerTestforSuffixFinder()

Dim i As Double
Dim NameStr As String
Dim LengthMeasure As Integer

NameStr = "PrettyPonies"
LengthMeasure = Len(NameStr)

    Do While i < 9
    i = i + 1
        If vbOK Then
   '3-character string created by using the Right() function
   MsgBox Right(NameStr + "-" + "00" & i, LengthMeasure + 4)
        Else: End
        End If
    Loop

i = i + 1
    Do While i >= 10 And i < 99
        If vbOK Then
           MsgBox Right(NameStr + "-" + "0" & i, LengthMeasure + 4)
        Else: End
        End If
        i = i + 1
    Loop

End Sub

为了简化您的实施,请尝试以下方法:

Sub MyCounter()
    Dim i As Double
    Dim NameStr As String
    Dim LengthMeasure As Integer
    Dim leadingZero As String

    NameStr = "PrettyPonies"
    LengthMeasure = Len(NameStr)

    For i = 1 To 99 Step 1
        If i > 9 Then leadingZero = "0" Else leadingZero = "00"

        MsgBox Right(NameStr + "-" + leadingZero & i, LengthMeasure + 4)
    Next i
End Sub

答案 2 :(得分:1)

尝试以下方法:`

Do While i < 100
    i = i + 1
    Debug.Print "XXX" & "-" & Format(i, "000")

Loop