2016-11-30 55 views
0

我在excel vba中设置了以下用户输入。被叫时的功能要求用户输入一个不大于9999的单个号码,或者用两个数字用破折号分隔的两个XXXX-XXXX格式的数字。在这种情况下,两种情况下的数字都不能大于9999,或者至少不应该大于9999。验证用户输入excel vba

目标是返回单个数字(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 
+1

*遗憾的是它没有返回一个数组,它返回一个错误。下标超出范围* - 哪一行返回错误?或者,也许更重要的是,当您从另一个子集调用此函数时,是否也将结果分配给变体对象类型? –

+0

如果声明一个带有开放括号的数组,在某些时候,你必须在代码中对其进行标注。另一种方法是声明'Dim numArr As Variant'。如果响应中没有破折号,则不会在任何地方为numArr分配值。这就是说,我看不到你的代码实际上实现了什么。 – SJR

+0

如果用户输入需要'-1'会怎么样?你如何从“-1”错误值中判断一个有效的“-1”?使用结构化错误处理而不是神奇的返回值,并避免使用“GoTo”。 –

回答

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