7thGalaxy
7thGalaxy

Reputation: 225

VBA Programmatically change object name

I've created a date picker which allows you to select multiple dates, and toggle them so no-one can book anything on those days.

In order to do this, I have 31 toggle buttons, and a month selector. When you select the month, each of the 31 buttons has to update, and get the value (toggled on or or) from a DLookup.

At the moment, I've got the code for this as a long list in the update event of the month picker

Private Sub cmbMonth_AfterUpdate()

    If IsNull(Me.cmbMonth) Then
        GoTo Subexit
    Else
        Imonth = CInt(Me.cmbMonth)
    End If

    Call Update_toggle(Me.Toggle1)
    Call Update_toggle(Me.Toggle2)
    Call Update_toggle(Me.Toggle3)
    Call Update_toggle(Me.Toggle4)

etc - up to toggle 31.

Is there a way of doing this with a loop?

I tried something along the lines of:

Dim toggle as Togglebutton
Dim I as integer
Dim strTogglename as String
set toggle = new togglebutton

I = 1

for 1 = 1 to 32

    strtogglename = "Me.Toggle" & I

    set toggle.name = strtogglename

    Call Update_toggle(Toggle)

next I

But I can't get it to work. Playing around with byref and byval don't seem to help.

Upvotes: 3

Views: 1585

Answers (4)

ddmmaaxx
ddmmaaxx

Reputation: 1

As much as I know it is not possible to programmatically edit a control's name. To achieve that, one must be inside the VBA editor. Only a caption may be edited in code.

Upvotes: 0

HansUp
HansUp

Reputation: 97101

Within the loop, you are able to derive the names of your controls as "Toggle" & I. So you can target the corresponding control object by referencing that item by name in the form's Controls collection.

'for 1 = 1 to 32
For I = 1 to 31
    Call Update_toggle(Me.Controls("Toggle" & I))
Next I

Upvotes: 1

RubberDuck
RubberDuck

Reputation: 12728

You can use the Form's Controls collection and check the type of each control as you loop. You're looking for acToggleButtons.

Dim cntrl As Control
For Each cntrl In Me.Controls
    If cntrl.ControlType = acToggleButton Then

        Update_toggle cntrl

    End If
Next

Upvotes: 2

Matteo NNZ
Matteo NNZ

Reputation: 12655

You need to store your objects inside a global collection at initialize time, for example:

Global Collection declaration

Dim allToggles As Collection

Initialize - storing objects in collection

Set allToggles = New Collection
With allToggles
    .Add Me.Toggle1
    .Add Me.Toggle2
    '...
    .Add Me.Toggle31
End With

Calling in loop

for I = 1 to 32

    Update_toggle allToggles(I)

next I

Upvotes: 2

Related Questions