Consulting

Results 1 to 6 of 6

Thread: Quality check of data in InputBox

  1. #1

    Quality check of data in InputBox

    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?

  2. #2
    VBAX Guru Kenneth Hobs's Avatar
    Joined
    Nov 2005
    Location
    Tecumseh, OK
    Posts
    4,956
    Location
      Dim d As Integer
      Do Until d >= 1900 And d <= 2100
        d = CInt(Application.InputBox("Enter Year", "Year 1900 to 2100", Type:=1))
      Loop

  3. #3
    Huh, that was quite a bit simpler. Thanks a lot for your help

  4. #4
    VBAX Sage
    Joined
    Apr 2007
    Location
    United States
    Posts
    8,728
    Location
    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

  5. #5
    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"?

  6. #6
    VBAX Sage
    Joined
    Apr 2007
    Location
    United States
    Posts
    8,728
    Location
    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

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •