Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 595
7thGalaxy Avatar asked Jul 04 '26 04:07

7thGalaxy


2 Answers

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
like image 73
RubberDuck Avatar answered Jul 06 '26 22:07

RubberDuck


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
like image 24
Matteo NNZ Avatar answered Jul 06 '26 21:07

Matteo NNZ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!