Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17


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

Posted on 2013-01-22
Medium Priority
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
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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 58
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.
What Is Blockchain Technology?

Blockchain is a technology that underpins the success of Bitcoin and other digital currencies, but it has uses far beyond finance. Learn how blockchain works and why it is proving disruptive to other areas of IT.

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 58
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 58

Accepted Solution

Jim Dettman (Microsoft MVP/ EE MVE) earned 1500 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

Migrating Your Company's PCs

To keep pace with competitors, businesses must keep employees productive, and that means providing them with the latest technology. This document provides the tips and tricks you need to help you migrate an outdated PC fleet to new desktops, laptops, and tablets.

Question has a verified solution.

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

It’s the first day of March, the weather is starting to warm up and the excitement of the upcoming St. Patrick’s Day holiday can be felt throughout the world.
Microsoft Access is a place to store data within tables and represent this stored data using multiple database objects such as in form of macros, forms, reports, etc. After a MS Access database is created there is need to improve the performance and…
Get people started with the utilization of class modules. Class modules can be a powerful tool in Microsoft Access. They allow you to create self-contained objects that encapsulate functionality. They can easily hide the complexity of a process from…
In Microsoft Access, learn the trick to repeating sub-report headings at the top of each page. The problem with sub-reports and headings: Add a dummy group to the sub report using the expression =1: Set the “Repeat Section” property of the dummy…

688 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