我在excel vba中设置了以下用户输入。调用时函数要求用户输入不大于9999的单个数字,或者输入格式为XXXX-XXXX的两个数字,其中两个数字用短划线分隔。在这种情况下,在任何一种情况下,数字都不能大于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
答案 0 :(得分:0)
这应该做:
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