A Sub that works on a Form will NOT work on a New Form Instance

MAIN ISSUE: A Sub that (successfully) writes captions to a series of command buttons on a first and/or only instance of a form does not work on any New Form instance.

I have an issue where I have written some code that will, upon the Load event of a Form, write the captions to a set of command buttons (42 of them!) by looking into a table and getting the value to use as the caption. It works great on the first instance of the form, but will not work on any New Instance of the form. (I am guessing that this is because the way I wrote my code, it is unclear which form is being addressed by the code if there is more than one instance of the form.)

Here is the code that I used to open the New Form Instance (pretty standard stuff that I probably got here on this very site somewhere.)

BEGIN CODE >>>>>>>>>>>

Public Function OpenFormInstance(FormName As String, Optional WhereCondition As String)

'Declare the Form Name
Dim frm As Form

Set frm = New Form_frm_add_edit_instrument

If WhereCondition <> "" Then
    frm.Filter = WhereCondition
    frm.FilterOn = True
End If

'Make the Form Visible
frm.Visible = True

'Alter Form's Caption
Dim varFormCaption As Variant
varFormCaption = "*" & Nz(frm.instr_vp_short_name.Value, Null) & "*"
frm.Caption = varFormCaption

'Need to add a reference to the form so it doesn't immediately close when the form variable goes out of scope

End Function

END CODE<<<<<<<<<<<<<<<

Here is the code that is to run upon the form's Load event:

BEGIN CODE>>>>>>>>>>>>>>>>>>>>>>
Public Sub LoadCommandButtonCaptions()
Dim strCurrentForm As String, strNewForm As String
strCurrentForm = Me.Form.Name
Dim strButtonCaption As String
Dim strButtonName As String
Dim strControlName As String

Dim intNext As Integer
Dim strNext As String

For intNext = 1 To 42
    strNext = Format(intNext, "0#")
    strButtonName = "cmd_ptb_REM" & strNext
    strControlName = "frmCurrent!" & strButtonName
    strButtonCaption = GetButtonCaption(strButtonName)
        With Forms(strCurrentForm).Controls(strButtonName)
        .Caption = strButtonCaption
    End With
Next intNext
End Sub

END CODE<<<<<<<<<<<<<<<<<<<<<<<<<<

And just in case it is relevant, here is the code for the function GetButtonCaption():

BEGIN CODE<<<<<<<<<<<<<<<<<<
Public Function GetButtonCaption(ButtonName As String) As String
Dim db As Database
Dim rs As DAO.Recordset
Dim strSql As String
Dim strButtonName As String
Dim varButtonCaption As Variant
'Dim GetButtonCaption As String

strButtonName = Right(ButtonName, 5)

'Open connection to current Access database
Set db = CurrentDb()
'Create SQL statement to retrieve value from GST table
strSql = "SELECT prog_text_button_caption FROM tbl_prog_text_buttons WHERE prog_text_button_name = '" & strButtonName & "';"
Set rs = db.OpenRecordset(strSql)
'Retrieve value if data is found
If rs.EOF = False Then
         varButtonCaption = Nz(rs("prog_text_button_caption"), "")
         varButtonCaption = "NF"
     End If

GetButtonCaption = varButtonCaption
Set rs = Nothing

End Function
END CODE<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

Any help is appreciated.
Who is Participating?
Jim Dettman (Microsoft MVP/ EE MVE)President / OwnerCommented:
OK, let's assume you have a generic function define like this:

Function LockControls(strFormName as string) as variant

 Your calling that function from the form and right now, you have it like this:

 varRet = LockControls(Me.Name)

 which fails because all instances have the same name.

 Instead, you would define it like this:

Function LockControls(frm As Form) as variant

and call it as:

 varRet = LockControls([Form])


varRet = LockControls([Me])

 You can get away with doing that (no collection needed) because your calling the code from the form's module and passing a object reference that points directly to this specific instance of the form.  As long as you don't pass a form name as a string, your set.

 But now what if your not calling a procedure from inside a form module?  Since you don't have a reference already (you don't have [Form] or [Me] available to you), now you do need the collection.   Let's say you wanted to lock the controls of every open form.  You would do this:

 Dim frm as Form_frm_add_edit_instrument

 For Each frm in mcolFormInstances
     varRet = LockControls(frm)
 Next frm

 All your routines that involve this form must accept a object reference, not the form name as a string in order to work properly.

 If your in a forms code module, you can simply use [Form] or [Me] to pass as a reference.

 If your not in a forms code module, then you must use the collection to get an object reference for a form.

  You can loop on the collection as I showed above, or refer to a specific form as long as you know it's handle, like this:

mcolFormInstances(Cstr(<handle value>)

 so from the debug window, I could do:

Debug.Print mcolFormInstances("1234").Name

 assuming 1234 was a valid handle.

Rey Obrero (Capricorn1)Commented:
set the focus to the new form instance

Set frm = New Form_frm_add_edit_instrument
Jim Dettman (Microsoft MVP/ EE MVE)President / OwnerCommented:

strCurrentForm = Me.Form.Name

Is why it's failing.  Multiple instances of forms all have the same name.

What you need to do is add a object reference to the collection.  You can use the window handle as a key. ie.

mcolFormInstances.Add Item:=Frm, Key:=frm.hWnd & " "

 You can then find the hwnd in the collection and have an object reference to manipulate the form.

 The other thing you want to do is add the instance (1st, 2nd, 3rd, etc) number to the forms caption.

  You then have two different ways to identify the form.

Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

dgheckAuthor Commented:
Thanks much.

I guess I am still unclear on how to actually reference the New Instance once I have used...

mcolFormInstances.Add Item:=Frm, Key:=frm.hWnd & " "
...to provide it with a unique identifier.

In other words, what replaces...

strCurrentForm = Me.Form.Name

...in the current code?

Thanks again for any further help.
Rey Obrero (Capricorn1)Commented:
be consistent of referring to the new instance of the form you created

Set frm = New Form_frm_add_edit_instrument
Jim Dettman (Microsoft MVP/ EE MVE)President / OwnerCommented:
<<In other words, what replaces...

strCurrentForm = Me.Form.Name

With a collection, you have two ways to refer to an item:

1. It's ordinal position

2. By key.

I suggested you change the caption to reflect the ordinal.  So if you parse the caption (or maybe create your own form property, say "instancenumber"), you can refer to it like this:

Dim frm as form

Set frm = mcolFormInstances(<instancenumber>)

or by it's key:

Set frm = mcolFormInstances(Me.hWnd)

However the problem with the first is that if an item is removed from the collection, then higher entires are adjusted downwards, which means all the captions would need to change.  That would be confusing for the users.

 So I would suggest you always go with the 2nd form and use the key (hwnd) to reterive the reference and leave the captions alone as simply a reference for the user.

 and btw, keys must be strings rather then numerics, so take that into account in the comments I made above.

dgheckAuthor Commented:
Okay, I have altered the code that creates the new form instance with:

mcolFormInstances.Add Item:=frm, Key:=CStr(frm.Hwnd)

....to create the unique identifier.

I still havent managed to decipher what I need to have in the code that fires on the Form's Load event. I know I need to refer to the unique form but I am afraid I just don't know the syntax well enough to supplant the various strCurrentForm and frmCurrent! variables with the Hwnd info to correctly identify the form.

Sorry I am being so thick on this. I haven't worked with objects/collections much.
Rey Obrero (Capricorn1)Commented:
my last post for you

download the sample file from


after opening the db,
select the topic

How to Open multiple instances of a form

you can also open the vba window and see the codes behind the click  event of the button
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.