Public variables are not REALLY public in VBA in Forms Public variables are not REALLY public in VBA in Forms vba vba

Public variables are not REALLY public in VBA in Forms


First comment:

Userform and Sheet modules are Object modules: they don't behave the same way as a regular module. You can however refer to a variable in a userform in a similar way to how you'd refer to a class property. In your example referring to fMyForm.bYesNo would work fine. If you'd not declared bYesNo as Public it wouldn't be visible to code outside of the form, so when you make it Public it really is different from non-Public. – Tim Williams Apr 11 '13 at 21:39

is actually a correct answer...


As a quick add-on answer to the community answer, just for a heads-up:

When you instantiate your forms, you can use the form object itself, or you can create a new instance of the form object by using New and putting it in a variable. The latter method is cleaner IMO, since this makes the usage less singleton-ish.

However, when in your userform you Call Unload(Me), all public members will be wiped clean. So, if your code goes like this:

  Dim oForm as frmWhatever  Set oForm = New frmWhatever  Call oForm.Show(vbModal)  If Not oForm.bCancelled Then  ' <- poof - bCancelled is wiped clean at this point

The solution I use to prevent this, and it is a nice alternative solution for the OP as well, is to capture all IO with the form (i.e. all public members) into a separate class, and use an instance of that class to communicate with the form. So, e.g.

  Dim oFormResult As CWhateverResult  Set oFormResult = New CWhateverResult  Dim oForm as frmWhatever  Set oForm = New frmWhatever  Call oForm.Initialize(oFormResult)  Call oForm.Show(vbModal)  If Not oFormResult.bCancelled Then  ' <- safe