+ Reply to Thread
Results 1 to 2 of 2

Thread: Repeating Procedure

  1. #1
    Registered User
    Join Date
    10-03-2010
    Location
    Wales
    MS-Off Ver
    Excel 2007
    Posts
    13

    Repeating Procedure

    I have a function that determines if an entry to a TextBox is numeric, a blank or something else. The IF THEN statement in the procedure runs the Function & responds accordingly to the result.
    I have to run five lines of code in the procedure for each TextBox that is on the Form & there are 10 TextBoxes in total. My problem is I’m trying to find a way of reducing the repeated code in the procedure for each TextBox (TextBox1, TextBox2, TextBox3, TextBox4………so on) is there a way?

    The Procedure Code for just 1 TextBox is….

    If IsNum(TextBox1.Text) = 0 Then
            MsgBox "Please Enter Only Numeric Values"
            TextBox1.SetFocus
            Exit Sub
    End If
    The Function Code is….

    Function IsNum(Num)
            If Not (IsNumeric(Num) Or Num = "") Then
                 IsNum = 0
            End If
    End Function

  2. #2
    Valued Forum Contributor blane245's Avatar
    Join Date
    02-20-2009
    Location
    Melbourne, FL
    MS-Off Ver
    Excel 2010
    Posts
    641

    Re: Repeating Procedure

    This code uses a common validation routine. You can do something similar for other types of validations. Put this in a Module:
    Option Explicit
    
    Function IsNum(Num) As Boolean
        IsNum = (IsNumeric(Num) Or Num = "")
    End Function
    
    Function ValidateNumber(theText As String) As Boolean
        If (Not IsNum(theText)) Then
            MsgBox "Please Enter Only Numeric Values"
            ValidateNumber = False
        Else
            ValidateNumber = True
        End If
    End Function
    
    Sub doit()
        UserForm1.Show
    End Sub
    This is the Exit event handler for textbox1 using the validation routine. put it in the userform and repeat it for each textbox you want to check.
    Private Sub TextBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean)
        Cancel = Not ValidateNumber(Me.TextBox1.Value)
    End Sub
    Bob
    Click my star if my answer helped you. Mark the thread as [SOLVED] if it has been.

+ Reply to Thread

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Bookmarks

Posting Permissions

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

Search Engine Friendly URLs by vBSEO 3.2.0