PDA

View Full Version : Common code with two userforms



tlangford
06-02-2008, 06:26 AM
Hi.

I have two userforms, frmA and frmB, which two checboxes that do precisely the same thing (it's not important what they do for my question).

When a button on each of the userforms is clicked, it calls the same sub which I've created in a common module. This sub evaluates whether the checkbox is true or false and then does some stuff. Here's the issue..

If I give both checkboxes on the two userforms the same name (e.g. chkDoSomething) then this should allow me to use the same code in the common sub, i.e.

if .chkDoSomething then 'Do something
Of course I need to tell it which userform the object is on, and here is my problem. If I manually edit the code to

if frmA.chkDoSomething then 'Do something
then it works fine, but I cannot find a way to substitute the userform name with a variable, such as

Dim theFormName as string
theFormName = "frmA"
if theFormName.chkDoSomething then 'Do something
I've also tried using the With statement, but that doesn't work either. The only way it will work is if I manually enter the name of the form. This means that I'd need duplicate code to do the same thing on both forms, which can't be right...

Please help, this is driving me nuts! I'm using Word 2003 by the way...

Oorang
06-02-2008, 09:47 AM
Try "Me":
If Me.chkDoSomething Then
Msgbox "Ha!"
End If

fumei
06-02-2008, 09:55 AM
You need to use an object. In your code theFormName is a string. To VBA there is no difference to you telling it:

If BlahBliddyDoDah.chkDoSomething

It is a string. Strings do not have a . property like a checkbox.

Declare objects for your userforms, and Set them.

Dim frm1 As MSForms.UserForm
Dim frm2 As MSForms.UserForm

Set frm1 = frmA
Set frm2 = frmB



How are you currently passing the checkbox to the Sub?

Norie
06-02-2008, 10:05 AM
Why do you have 2 apparently identical userforms?

What does the other code do?

Why are you using it to evaluate the status of the checkboxes?

fumei
06-02-2008, 10:13 AM
I think these are very legitimate questions as well.