我试图获取一个输入框来验证用户将输入的条目。
我正在使用以下脚本,但无法使验证工作,任何帮助将不胜感激。
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
答案 0 :(得分:3)
虽然不建议使用内置的子名称,但您可以按照以下方式执行操作。
首先,您需要将InputBox 类型更改为 2 (字符串),因为您要与String进行比较。然后你应该创建一个函数来检查输入是否是管理器列表的一部分。
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
答案 1 :(得分:1)
没有将InputBox与Excel一起使用,但我想它与Access的非常相似。我使用以下方法验证inputbox:
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
,除非它们被赋予变量,在这种情况下我建议添加前缀,这样更明显,例如{{1而不是lBen
,所以你可以很容易地看到变量类型的差异。
strBen