2014-02-24 72 views
1

我試圖獲取一個輸入框來驗證用戶將輸入的條目。驗證輸入框的條目

我使用下面的腳本,但不能得到驗證工作,任何幫助將不勝感激。

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 

回答

3

雖然建議不建議使用與建立在一個名稱相同的子名稱,你可以做下面的樣子後。

首先,你需要到的InputBox 類型更改爲(字符串),因爲你是用字符串比較。然後你應該做一個函數來檢查輸入是否是經理列表的一部分。

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

我喜歡使用數組,我應該抓住那個。您可以使用'If IsError(Application.Match(Trim(sTxt),aManagers,False))Then',如果條目不在數組中,則返回true。 – Simon1979

+0

感謝您的提示!對於其他讀者:它應該是'Application.WorksheetFunction.Match()' – PatricK

1

還沒有使用Excel的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,除非他們被賦予變量,在這種情況下,我會建議添加前綴,所以它更明顯,如lBen而不是strBen,所以你可以很容易地看到變量類型的差異。

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 
+0

OK看起來不錯,我怎麼那麼有STRM的輸入值成片被稱爲 「PID」 細胞 「G9」。謝謝。 –

+0

'worksheets(「PID」)。Range(「G9」)= strM'應該完成這項工作。 – Simon1979

+0

感謝所有的好現在。 –