验证输入框的输入
Posted
技术标签:
【中文标题】验证输入框的输入【英文标题】:Validate entry of an input box 【发布时间】:2014-03-25 11:17:26 【问题描述】:我试图获取一个输入框来验证用户将输入的条目。
我正在使用以下脚本,但无法使验证正常工作,我们将不胜感激。
Sub inputbox()
Dim Manager As Long
On Error Resume Next
Application.DisplayAlerts = False
Manager = Application.inputbox(Prompt:="Please enter a manager.", Title:="Pick A Manager Name", Type:=1)
On Error GoTo 0
Application.DisplayAlerts = True
If Manager = "" Then
Exit Sub
ElseIf Manager <> Ben, Cameron, Chris, Martin, Peter Then
MsgBox "Incorrect Name, pick a new one!"
Else
MsgBox "Your input was " & Manager
End If
End Sub
【问题讨论】:
【参考方案1】:虽然不建议使用与内置的 Sub 名称相同的名称,但您可以按照以下方式进行操作。
首先您需要将 InputBox Type 更改为 2(字符串),因为您正在与字符串进行比较。然后你应该创建一个函数来检查输入是否是经理列表的一部分。
Sub inputbox()
On Error Resume Next
Dim Manager As String
Manager = Application.inputbox(Prompt:="Please enter a manager name:", Title:="Pick A Manager Name", Type:=2)
If Manager <> "" Then
If IsManager(Manager) Then
MsgBox "Your input was " & Manager
Else
MsgBox "Incorrect Name, pick a new one!"
End If
End If
End Sub
Private Function IsManager(sTxt As String) As Boolean
Dim aManagers As Variant, oItem As Variant, bAns As Boolean
aManagers = Array("Ben", "Cameron", "Chris", "Martin", "Peter")
bAns = False
For Each oItem In aManagers
If LCase(oItem) = LCase(Trim(sTxt)) Then
bAns = True
Exit For
End If
Next
IsManager = bAns
End Function
更新(Simon1979 建议的改进版本):
Private Function IsManager(sTxt As String) As Boolean
On Error Resume Next
Dim aManagers As Variant
aManagers = Array("Ben", "Cameron", "Chris", "Martin", "Peter")
IsManager = Not IsError(Application.WorksheetFunction.Match(Trim(sTxt), aManagers, 0))
End Function
【讨论】:
我喜欢使用数组,我应该抓住那个。您也可以使用If IsError(Application.Match(Trim(sTxt), aManagers, False)) Then
,而不是循环遍历数组,如果条目不在数组中,则返回true。
感谢您的提示!致其他读者:应该是Application.WorksheetFunction.Match()
【参考方案2】:
没有在 Excel 中使用过 InputBox,但我想它会与 Access 非常相似。我使用下面的方法来验证输入框:
Dim strM as string
EnterManager:
strM = InputBox("Enter Manager.")
If StrPtr(strM) = 0 Then 'Cancel was pressed
' Handle what to do if cancel pressed
Exit Sub
ElseIf Len(strM) = 0 Then 'OK was pressed with nothing entered
MsgBox "You must enter a Manager."
GoTo EnterBuyer
End If
要添加您的条件,您可以添加另一个If
,我不确定您是否可以使用检查名称列表的方法。也不明白如何将长 Manager
与名称列表 Ben, Cameron, Chris, Martin, Peter
进行比较,除非它们被分配了变量,在这种情况下,我建议添加前缀以便更明显,例如 lBen
而不是 @ 987654326@ 这样就可以很容易看出变量类型的不同了。
If strM <> "Ben" And strM <> "Cameron" And strM <> "Chris" And strM <> _
"Martin" And strM <> "Peter" Then
MsgBox "Incorrect Name, pick a new one!"
Else
MsgBox "Your input was " & strM
End If
【讨论】:
OK 看起来不错,然后我如何将 strM 的值输入到单元格“G9”中名为“PID”的工作表中。谢谢。以上是关于验证输入框的输入的主要内容,如果未能解决你的问题,请参考以下文章