[英]Validating user input excel vba
我在excel vba中設置了以下用戶輸入。 調用該函數時,要求用戶輸入不大於9999的單個數字,或者輸入格式為XXXX-XXXX的兩個數字,其中兩個數字之間用短划線隔開。 在那種情況下,無論哪種情況,數字都不能大於9999,或者至少不應該大於9999。
目標是返回單個數字(IE 50)或范圍(IE低值是50,高值是75)。 當前,它應該返回一個數組,其中第一個位置是低值,第二個位置是高值。 或者,如果用戶僅輸入一個數字,則應在數組的第一個位置返回該數字。
當前,它檢查A)用戶是否輸入了數字,B)該數字不超過4位數字。
不幸的是,它沒有返回數組,而是返回了錯誤。 下標超出范圍。
另外,是否還有其他可能的用戶輸入應在此處進行檢查? 該應用程序不會被人們廣泛使用,但是我也想將潛在的錯誤減到最少。
Public Function getUserInput() As Variant
'this function gets a user input from an input box and puts it out into the proper format
Dim inputString As String
Dim numArr() As String
Dim i As Long
' On Error GoTo NotValidInput
inputString = Trim(InputBox("Enter the rows you'd like to print"))
'has the user entered a dash into their user input
If InStr(inputString, "-") > 0 Then
numArr() = Split(inputString, "-")
If UBound(numArr) <> 1 Then
GoTo NotValidNumberFormat
End If
If (IsNumeric(numArr(0)) And Len(numArr(0)) <= 4) And (IsNumeric(numArr(1)) And Len(numArr(1)) <= 4) Then
getUserInput = numArr
Exit Function
Else
GoTo NotValidNumberFormat
End If
'no dash
'60
Else
If (IsNumeric(CInt(inputString))) And Len(inputString) <= 4 Then
getUserInput = numArr
Exit Function
Else
GoTo NotValidNumberFormat
End If
End If
Exit Function
NotValidNumberFormat:
'if the conversion failed, return error
MsgBox ("Please enter the number in a valid format - either a single number no larger than 9999 or two numbers no larger than 9999 separated by only one dash (IE XX-XX)")
getUserInput = -1
End Function
這應該做:
Public Function getUserInput() As Variant
'this function gets a user input from an input box and puts it out into the proper format
Dim numArr As Variant
Dim goOn As Boolean
Do
numArr = Split(WorksheetFunction.Trim(InputBox("Enter the rows you'd like to print in the format 'nnnn' or 'nnnn-mmmm'")), "-")
Select Case UBound(numArr)
Case 0
goOn = Format(numArr(0), "0000") Like "####"
Case 1
goOn = Format(numArr(0), "0000") Like "####" And Format(numArr(1), "0000") Like "####"
End Select
If Not goOn Then MsgBox "Please enter the number in a valid format - either a single number no larger than 9999 or two numbers no larger than 9999 separated by only one dash (ex: XX-XX)"
Loop While Not goOn
getUserInput = numArr
End Function
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.