In VB6, I have a main form (frmMain) with three subsidary forms. The latter set various properties on frmMain, e.g. frmMain.NoCopies = x

I have a number of procedures that I want to put this in, so I need to pass the name of the form as a variable - otherwise I will end up with three subsidiary forms for each procedure.

Is it possible?

(I am trying to pass the info as public variables, but it seems to be a long way round)

Regards
pitters

Dani AI

Generated

Short answer: pass an object reference to the procedure (or expose a setter on the main form). Passing a string with the form name does not give you a typed object you can call custom properties on without extra work.

A few practical patterns that work in VB6:

  • Strongly typed (recommended): have your shared routine accept the actual form class so you get compile-time access and IntelliSense. This is the safest and fastest at runtime.
Public Sub SetPrintCopies(ByRef frmRef As frmMain, ByVal cnt As Integer)
    frmRef.PrintCopies = cnt
End Sub
  • Late binding by name: if you only have the form name at runtime, fetch the loaded instance from the Forms collection and use late binding (or CallByName) to set the property. Remember the form must be loaded first.
Public Sub SetCopiesByName(formName As String, copiesCount As Integer)
    Dim f As Object
    Set f = Forms(formName)
    CallByName f, "PrintCopies", VbLet, copiesCount
End Sub

Notes and troubleshooting

  • was right to suggest using a form reference, but declaring a variable as the generic Form class will not expose form-specific properties. Declare the variable as the specific form type or use Object + CallByName for late binding.
  • ’s Forms collection approach works, but prefer using the form name string (Forms("frmMain")) rather than numeric indices and be sure the form is loaded.
  • Prefer exposing a public procedure or Property Let/Get on frmMain (for example, Public Sub ApplyCopies(count As Integer)) instead of reaching into public variables from other modules; that keeps the form’s state encapsulated and reduces coupling.
  • Use Set when assigning object variables, and be aware of default instances vs. created instances (New).

Recommended Answers

All 4 Replies

Did you try passing

me.Name

Hi Hussain,

My problem is not in passing the name but in using the variable in the subsidiary form - e.g. instead of using the code frmMain.NoCopies = 2
I want to be able to use (varaible).NoCopies = 2

Regards
Tony

Try something like this:

Dim frm As Form

'frm = some form reference....
frm = frmMain

frm.NoCopies = 2

Dim a As Form
Set a = Forms(1)
MsgBox a.NoofCopies

'I hope it will help.
'Note: make sure the form is loaded

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.