1

Is there a way I can write my Userform code in a module?

The reason I'm asking this is because I have a multi-page userform with an increasingly massive amount of code behind it. For organizational purposes, I'd like to be able to space out the code in different modules. But I don't know if this can be done for userforms (aside from calling a subroutine from the userform event).

Is there a way to write UserForm code in a module without having to call the subroutine from the userform code?

Elias
  • 723
  • 3
  • 11
  • 18

2 Answers2

2

Actually it's simple. The code in your form module can call subroutines in other modules. So simply cut your code for a particular routine and paste it into another module, name it appropriately, and then in the form module place the name of the routine to call it. The only gotcha is that when the code is in a seperate module you can't use the Me keyword. If you use that in your code then pass the form as an argument and replace Me with your variable. A simplistic example: Assume you orinally have

Sub OK_Click()
    If Me.txtName<>"" then
          MsgBox "Ok",vbOkOnly,"It Worked"
    End If
End Sub

Then you can create the following in a seperate module:

Sub DoOkClick( f as UserForm)
   if f.txtname<>"" then
       MsgBox "Ok",vbOkOnly,"It Worked"
   End If
End Sub

and then replace the button click code with

Sub Ok_Click
  DoOkClick Me
end sub
Andy Brazil
  • 134
  • 2
0

An approach is outlined here that involves defining a Class and adding controls to the form dynamically, which are then associated with Events of the Class.

From you description, though, it sounds like your UserForm is doing too much. I suggest that you consider creating other forms, rather than trying to do everything from a single form. You could, perhaps, create a Class to store properties (and behaviours) that are common to the two or three forms that you might create. Instantiate the Class when the first (main) form is opened.

Community
  • 1
  • 1
Andy G
  • 19,232
  • 5
  • 47
  • 69