Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resetting form in VBA

Tags:

vba

I have a VBA form with a variety of selection options including drop downs, text fields, checkboxes and radios.

I just wanted to know about the best way to clear all these fields with a button press. A friend of mine has tried to help by emailing me the code below but unfortunately it doesn't work, I have checked the variable names.

Any advice on how I can improve it?

Thanks in advance.

Private Sub btnReset_Click()

Unload Me
UserForm.Show

End Sub

Here is the other code for the userform.

Dim DeptCode 'Holds department code

Private Sub UserForm_Initialize()

    Dim c_deptCode As Range
    Dim c_deptName As Range
    Dim deptCodes As Variant
    Dim deptNames As Variant

    Dim ws_dept As Worksheet
    Set ws_dept = Worksheets("lookupDept")

    ' Assign each range to an array containing the values
    deptCodes = Choose(1, ws_dept.Range("deptCode"))
    deptNames = Choose(1, ws_dept.Range("deptName"))

    For i = 1 To ws_dept.Range("deptCode").Rows.Count
        ' Create the combined name (code + space + name)
        CombinedName = deptCodes(i, 1) & " - " & deptNames(i, 1)
        cbo_deptCode.AddItem CombinedName
    Next i

End Sub
like image 347
methuselah Avatar asked Oct 10 '12 14:10

methuselah


People also ask

How do you clear a form in Excel?

To clear all contents, formats, and comments that are contained in the selected cells, click Clear All. To clear only the formats that are applied to the selected cells, click Clear Formats. To clear only the contents in the selected cells, leaving any formats and comments in place, click Clear Contents.

What is reset in VBA?

The Reset statement closes all active files opened by the Open statement and writes the contents of all file buffers to disk.


1 Answers

I think when it hits the Unload Me line, code execution stops and that's why it's not working for you. Here's a generic event procedure to reset all (most) of the controls on the form.

Private Sub cmdReset_Click()

    Dim ctl As MSForms.Control

    For Each ctl In Me.Controls
        Select Case TypeName(ctl)
            Case "TextBox"
                ctl.Text = ""
            Case "CheckBox", "OptionButton", "ToggleButton"
                ctl.Value = False
            Case "ComboBox", "ListBox"
                ctl.ListIndex = -1
        End Select
    Next ctl

End Sub

It doesn't repopulate the ComboBoxes and ListBoxes, just clears the selection, which is what I assume you want.

like image 80
Dick Kusleika Avatar answered Sep 28 '22 11:09

Dick Kusleika