2016-11-30 126 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