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

Posted on 2013-01-22
Last Modified: 2013-06-22
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.
Question by:dgheck
  • 3
  • 3
  • 2
LVL 120

Expert Comment

by:Rey Obrero (Capricorn1)
ID: 38806518
set the focus to the new form instance

Set frm = New Form_frm_add_edit_instrument
LVL 57
ID: 38806535

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.


Author Comment

ID: 38806938
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 & " " provide it with a unique identifier.

In other words, what replaces...

strCurrentForm = Me.Form.Name the current code?

Thanks again for any further help.
Backup Your Microsoft Windows Server®

Backup all your Microsoft Windows Server – on-premises, in remote locations, in private and hybrid clouds. Your entire Windows Server will be backed up in one easy step with patented, block-level disk imaging. We achieve RTOs (recovery time objectives) as low as 15 seconds.

LVL 120

Expert Comment

by:Rey Obrero (Capricorn1)
ID: 38806975
be consistent of referring to the new instance of the form you created

Set frm = New Form_frm_add_edit_instrument
LVL 57
ID: 38807071
<<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.


Author Comment

ID: 38807426
Okay, I have altered the code that creates the new form instance with:

mcolFormInstances.Add Item:=frm, Key:=CStr(frm.Hwnd) 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.
LVL 120

Expert Comment

by:Rey Obrero (Capricorn1)
ID: 38807475
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
LVL 57

Accepted Solution

Jim Dettman (Microsoft MVP/ EE MVE) earned 500 total points
ID: 38807544
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.


Featured Post

U.S. Department of Agriculture and Acronis Access

With the new era of mobile computing, smartphones and tablets, wireless communications and cloud services, the USDA sought to take advantage of a mobilized workforce and the blurring lines between personal and corporate computing resources.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In the previous article, Using a Critera Form to Filter Records (, the form was basically a data container storing user input, which queries and other database objects could read. The form had to remain op…
Phishing attempts can come in all forms, shapes and sizes. No matter how familiar you think you are with them, always remember to take extra precaution when opening an email with attachments or links.
Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…
With Secure Portal Encryption, the recipient is sent a link to their email address directing them to the email laundry delivery page. From there, the recipient will be required to enter a user name and password to enter the page. Once the recipient …

776 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question