Results 1 to 3 of 3
  1. #1
    5 Star Lounger
    Join Date
    Nov 2004
    Wilmington, North Carolina, USA
    Thanked 0 Times in 0 Posts
    I'm trying to use a button's 'click' event to reset all the text boxes on my form. I've tried many iterations of the following:

    Dim txt As Control
    For Each txt In Me.Controls
      If TypeOf txt Is TextBox Then txt.Text = ""

    It doesn't do anything. If I substitute the clearing action with MsgBox("test"), I still don't get anything, so I feel like for some reason the code isn't actually looking at the collection of controls on the form, but I don't know how to fix it. I could simply list the 27 text boxes and set them all = Nothing, but that's bad practice.
    "If you spend more on coffee than on IT security, then you will be hacked. What's more, you deserve to be hacked." -Richard Clarke

  2. #2
    Super Moderator RetiredGeek's Avatar
    Join Date
    Mar 2004
    Manning, South Carolina
    Thanked 1,608 Times in 1,452 Posts
    Quote Originally Posted by NYIntensity View Post
    but that's bad practice.
    I assume by your comment that you are using a variable/control naming convention. Thus why not try:
    Dim txt As Control
    For Each txt In Me.Controls
      If Left$(,2) = "tb" Then txt.Text = ""
    or something similiar. Sorry, I can't test this as I don't have Visual Studio but logically it should work.
    May the Forces of good computing be with you!


    PowerShell & VBA Rule!

    My Systems: Desktop Specs
    Laptop Specs

  3. #3
    Super Moderator
    Join Date
    Dec 2000
    New York, NY
    Thanked 29 Times in 27 Posts

    Your original code works just fine when I test it here (as does Retired Geek's).

    If you're substituting a simple MsgBox statement, and the message box doesn't appear when you click the button, that doesn't mean that the controls code isn't working - it means that the code in the button Click procedure isn't running at all.

    The most common cause for code in a button Click procedure to not run, is if the name of the button, as referenced in the procedure signature, is not identical to the actual name of the button.
    One way this can happen is if you create a new button - which gets a default name like CommandButton1 - and you then create a button click procedure for that button - so the procedure will be named "Private Sub CommandButton1_Click()"

    If you later go and rename the button to something meaningful like "cmdClearTextboxes", but don't change the name in the Click procedure's signature, then the Click procedure code won't run when you click the button.

    Any chance something like that is happening?


Posting Permissions

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