在执行宏之前,如何输入InputBox?

时间:2017-07-18 18:43:07

标签: excel vba excel-vba

执行宏后,我的宏需要输入。但是,如果用户按下取消,宏将在没有此信息的情况下执行,这会在数据中留下漏洞。这是我最好的猜测,但它不会阻止用户取消并仍然执行:

        Do Until Not IsEmpty(myWknum)
        DoEvents

            myWknum = InputBox("Please enter week number")

        Loop

3 个答案:

答案 0 :(得分:2)

这将强制一个值,该值必须是数字:

Sub t()
Dim myWknum As String

Do While myWknum = "" Or Not IsNumeric(myWknum)
    myWknum = InputBox("Please enter week number")
Loop
End Sub

这样,更加冗长(并且可能更高效),将强制用户输入1到52之间的数字:

Sub t()
Dim myWknum As String

Do While myWknum = "" Or Not IsNumeric(myWknum)
    myWknum = InputBox("Please enter week number")
Loop

If myWknum < 1 Or myWknum > 52 Then
    Do While myWknum < 1 Or myWknum > 52
        myWknum = InputBox("Please use a valid week number. (>= 1 or <= 52)")
    Loop
End If

End Sub

答案 1 :(得分:1)

如果,当用户取消InputBox时,您希望退出子例程而不进一步处理,请使用Exit Sub语句:

Sub Test
    Dim myWkNum As String
    myWkNum = InputBox("Please enter week number")
    If myWkNum = "" Then Exit Sub
    '...
    'other code
    '...
End Sub

或者,通过一些有效性测试:

Sub Test
    Dim myWkNum As String
    Do
        myWkNum = InputBox("Please enter week number")
        If myWkNum = "" Then
            Exit Sub
        ElseIf IsNumeric(myWkNum) Then
            If myWkNum > 0 And myWkNum < 54 And Int(myWkNum) = myWkNum Then
                Exit Do
            End If
        End If
    Loop
    '...
    'other code
    '...
End Sub

答案 2 :(得分:0)

Loop行之前添加此内容。

if myWknum="" then Exit Do