PDA

View Full Version : [SOLVED] Quality check of data in InputBox



EirikDaude
12-10-2013, 11:27 AM
I have the following code for checking if the data put into an inputbox is a valid year (between 1990 and 2100):

Sub klikk()
Dim år As Long: år = 0
Dim inndata As String

Do While år > 2100 Or år < 1990
inndata = InputBox("Skriv inn året du vil lage skiftplan for.", "År", Year(Date) + 1)
If IsNull(inndata) Then
Exit Sub
ElseIf Len(inndata) < 1 Then
år = 0
ElseIf Not IsNumeric(inndata) Then
år = 0
Else
år = CLng(inndata)
End If
Loop
End Sub
While I think it works well enough, I was wondering if any of you guys could think of a way to shorten the code (e.g. some way to combine the two else-if statements to one), or if there are any possibilities for invalid input which I have forgotten about?

Kenneth Hobs
12-10-2013, 01:54 PM
Dim d As Integer
Do Until d >= 1900 And d <= 2100
d = CInt(Application.InputBox("Enter Year", "Year 1900 to 2100", Type:=1))
Loop

EirikDaude
12-10-2013, 02:23 PM
Huh, that was quite a bit simpler. Thanks a lot for your help :)

Paul_Hossler
12-10-2013, 02:42 PM
I'd include an escape clause to avoid infinite loop (just in case)



Dim d As Integer

d=-1
Do Until (d >= 1900 And d <= 2100) or d = 0
d = CInt(Application.InputBox("Enter Year, 0 to Exit", "Year 1900 to 2100", Type:=1))
Loop

if d = 0 then Exit Sub ' For example




Paul

EirikDaude
12-10-2013, 03:35 PM
Yeah, I'd actually added that after messing up one of my conditionals in the code I posted in the first post. One small issue I see with your code, is that there doesn't seem to be any handling of the user pushing the cancel-button in the inputbox. I think when you use application.inputbox pushing cancel will return "false"?

Paul_Hossler
12-10-2013, 04:08 PM
Actually, I since Ken has the CInt() there as well as Type:=1, a [Cancel] or [X] should come back as a 0 also.


Paul