带有Numbers的MsgBox + InputBox,用If验证输入数字

时间:2017-09-11 11:12:36

标签: excel-vba vba excel

新手提醒。我正在使用MsgBoxInputBox组合,询问用户是否要删除具有指定值(输入框)的行(msgbox)。我正在循环它,直到我在vbNo中得到Msgbox,这似乎有效,但是InputBox用户值验证似乎不起作用。
我已经读过,Inputbox将值识别为String,所以不确定这是否是一个问题?

我的疑问

1)我想限制用户只在输入框中输入数字,输入框也不超过4位数。我正在使用If语句,但没有工作。我正在考虑将一个输入框类型分配给整数,并且它将输入限制为数字,但如果用户输入错误而不是所有人都知道他们做错了什么,则没有警告。

2)当我放置与If UserValue = vbNullString Then GoTo Continue相反的行If UserValue <> vbNullString Then GoTo StoreEntered时 - 程序不起作用,是否有区别?任何建议都非常赞赏。

3) UPD 我刚尝试点击vbYes on Mgsbox然后点击Cancel on InputBox,我发誓之前有效,但似乎不再有用了。我原本以为引用vbNullString会解决不输入任何内容并单击OK或只是取消inputBox的问题。

这是我的代码

Dim UserValue As Integer
Dim UserReply As Variant

KeepLoop:
Do
UserReply = MsgBox(Prompt:="Do you want any store transactions removed?", Buttons:=vbYesNo, Title:="Stores removed")
    If UserReply = vbNo Then GoTo Continue
    If UserReply = vbYes Then GoTo UserInputReqd
Loop Until UserReply = vbNo

UserInputReqd:
UserValue = Application.InputBox(Prompt:="Enter any store number you want removed from the file. Otherwise click Cancel", _
                Title:="CHOSE STORES TO RUN OR DELETE") ', Type:=1)

        If UserValue <> vbNullString Then GoTo StoreEntered 'If user left line blank and clicked 'Ok' or clicked 'Cancel'
        If Not IsNumeric(UserValue) Then
                MsgBox "You must enter a numeric value"
        If Len(UserValue) > 4 Then
                MsgBox "Max store number is 4 digits", vbCritical
        End If
        End If

StoreEntered:
r = 100000
Do
If Sheets(csv_sht).Cells(r, 1) = UserValue Then Sheets(csv_sht).Rows(r).EntireRow.Delete
r = r - 1
Loop Until r = 1
GoTo KeepLoop

Continue: 'Next step, continue as normal.
==Code here==

End Sub

1 个答案:

答案 0 :(得分:0)

如果您不输入商店编号,我不完全清楚确切的消息流应该是什么,但是这样的事情应该简化:

Dim UserValue             As Variant
Dim UserReply             As Variant
Do
    UserReply = MsgBox(Prompt:="Do you want any store transactions removed?", Buttons:=vbYesNo, Title:="Stores removed")
    If UserReply = vbYes Then

        UserValue = InputBox(Prompt:="Enter any store number you want removed from the file. Otherwise click Cancel", _
                                         Title:="CHOSE STORES TO RUN OR DELETE")
        If UserValue = vbNullString Then
            ' do nothing
        ElseIf Not IsNumeric(UserValue) Then
                MsgBox "You must enter a numeric value"
        ElseIf Len(UserValue) > 4 Then
                MsgBox "Max store number is 4 digits", vbCritical
        Else
            For r = 100000 To 1 Step -1
                If Sheets(csv_sht).Cells(r, 1) = CLng(UserValue) Then Sheets(csv_sht).Rows(r).EntireRow.Delete
            Next r
        End If
    End If
Loop Until UserReply = vbNo
'Next step, continue as normal.