输入框阻止用户在值为空时按回车键

Inputbox prevent user from pressing enter when value is blank

我有以下代码: Range("P" & Rows.Count).End(xlUp).offset(1).Value = InputBox("INTRODUCE ACT JUSTIFICATIV") 用户必须在输入框中输入字母

如果输入框中的值为空白并显示个性化错误消息,我想防止用户意外按下 enter。

然后按取消按钮退出子程序。

将您的用户输入设置为一个变量,然后测试它是否有效。

Dim usrInput as String

Do
    usrInput = InputBox("INTRODUCE ACT JUSTIFICATIV")

    If usrInput = vbNullString Then
        MsgBox "Your Error Message"
    End If
Loop While usrInput = vbNullString

请尝试下一种方法:

Sub testInputBoxValidate()
  Dim strInpB As String
  strInpB = InputBox("INTRODUCE ACT JUSTIFICATIV")
  If strInpB = "" Then MsgBox "You did not introduce anything!": Exit Sub
  Range("P" & Rows.count).End(xlUp).Offset(1).Value = strInpB
End Sub

以及强制用户输入内容的变体:

Sub testInputBoxValidate()
  Dim strInpB As String
Start:
  strInpB = InputBox("INTRODUCE ACT JUSTIFICATIV")
  If strInpB = "" Then MsgBox "You did not introduce anything!": GoTo Start
  Range("P" & Rows.count).End(xlUp).Offset(1).Value = strInpB
End Sub

我还建议您尝试更多其他检查。例如,'ACT JUSTIFICATIV' 不能有特定的长度(位数)?特定模式,如“xxxx###”,其中“###”是三 (x) 位数字?

您可以使用 Application.InputBox,这会给您更多的控制权。系统将提示用户,直到他们输入 non-blank 字符串或按取消或 x 按钮

Dim vInput As Variant: vInput = ""
Do
    vInput = Application.InputBox("INTRODUCE ACT JUSTIFICATIV", Type:=2) '2 -> String type
    If vInput = False Then 'User pressed Cancel or x button
        Exit Do
    ElseIf Len(vInput) > 0 Then 'User has entered non-blank value
        Range("P" & Rows.Count).End(xlUp).Offset(1).Value = vInput
        Exit Do
    End If
Loop

我认为您不能仅在输入内容时强制关闭 InputBox。相反,将结果读入变量并循环直到输入有效内容

Dim answer as string, okay As Boolean
answer = ""
okay = False
Do While Not okay
    answer = InputBox("INTRODUCE ACT JUSTIFICATIV")
    On Error Resume Next
    okay = Range(answer & "1").Address <> ""
    On Error GoTo 0
Loop

现在,输入框将弹出,直到输入有效的列。