button to check if fields on form do not equal blank

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • p4nny1984
    New Member
    • Sep 2015
    • 10

    button to check if fields on form do not equal blank

    Hi,

    I have a form with around 10 fields..

    When the user clicks the "add record button"
    I would like a message box to appear to say which fields need responses (field = "") and it will cancel the event.

    Hope this is clear
  • jimatqsi
    Moderator Top Contributor
    • Oct 2006
    • 1293

    #2
    There are several ways you could approach this. One would be the verbose one, like this (each method requires adding code to the top of the On_Click event for the button:

    Code:
    dim bErr as boolean
    bErr=false
    If len(nz(me.textbox1))=0 then bErr=true
    If len(nz(me.textbox2))=0 then bErr=true
    If len(nz(me.textbox3))=0 then bErr=true
    ...
    if bErr then
        msgbox "At least one field has been left blank"
        exit sub
    end if
    Or, a much more elegant solution would be something like this. Decide on a convention to use that will identify each of these problem boxes (It is assumed some text boxes might be okay to be blank). Your convention might be to name these text boxes in a similar manner. I prefer to use the Tag property. Set the Tag property for each required field to some value, like "required." Then your code could look like this
    Code:
    dim ctl as control
    dim bErr as boolean
    for each ctl in me.Controls
        if ctl.tag = "required" and len(nz(ctl.value))=0 then bErr=true
    next
    if bErr then 
        msgbox "At least one field has been left blank"
    end if
    Or this would add the names of the fields that are blank
    Code:
    dim ctl as control
    dim bErr as boolean
    dim msg as string
    
    for each ctl in me.Controls
        if ctl.tag = "required" and len(nz(ctl.value))=0 then 
            bErr=true
            msg = msg & ctl.name & vbnewline
        end if
    next
    if bErr then 
        msgbox "These fields have been left blank." & vbnewline & msg
        exit sub
    end if
    And there are numerous other ways to approach this.

    Jim

    Comment

    • p4nny1984
      New Member
      • Sep 2015
      • 10

      #3
      Many thanks for this...

      What is me.controls? Is this the form name?
      Also,ctl.name.. ? is the name of the text

      Comment

      Working...