I was writing some code that required the user to input a number, which was then stored in a variable. While testing the code I input a number larger than the variable type would allow and I got an variable overflow error. So I wrote this code to prevent that from happening. It works, but I was hoping there was a more concise way to do it, or even a function already part of VBA that I could use.
Sub PreventOverflow()
Dim IsThisANumber As String
Dim Number As Integer
Dim PreventOverflow As Long
Dim Cancel As VbMsgBoxResult
Number = 0
PreventOverflow = 0
IsThisANumber = InputBox("Enter a number less than 32768")
Do While Number = 0
Do While PreventOverflow = 0
If IsNumeric(IsThisANumber) = True Then
If Len(IsThisANumber) < 6 Then
PreventOverflow = IsThisANumber
Else
IsThisANumber = InputBox("Your number was not less than 32768" & vbNewLine & "Please enter a number less than 32768")
PreventOverflow = 0
End If
ElseIf IsThisANumber <> "" Then
IsThisANumber = InputBox("Your did not enter a number" & vbNewLine & "Plese enter a number less than 32768")
PreventOverflow = 0
Else
Cancel = MsgBox("You did not enter a number. Do you want to continue?", vbYesNo)
If Cancel = vbNo Then
Exit Sub
Else
IsThisANumber = InputBox("Enter a number less than 32768")
PreventOverflow = 0
End If
End If
Loop
If PreventOverflow < 1 Or PreventOverflow > 32767 Then
IsThisANumber = InputBox("Your number was not less than 32768" & vbNewLine & "Please enter a number less than 32768")
PreventOverflow = 0
Else
Number = PreventOverflow
End If
Loop
End Sub
Function
procedure that returns the user input? \$\endgroup\$Function
instead of aSub
would the it still work in the same way? I guess my question is, what is the difference betweenFunction
andSub
? But yes, ideally this would be a function, that I could call. \$\endgroup\$Function
is a procedure that returns a value to the caller, much likeLen
,IsNumeric
,InputBox
andMsgBox
are. You would have to remove theDim PreventOverflow As Long
declaration though, because it having the same name as the function it's declared in would be a compile error (duplicate definition in current scope), because you assign a function's return value by assigning the function's identifier - so you can't have a local variable in a function with the same name as that function. \$\endgroup\$