Home > Software engineering >  Set Object Name with Variable in VBA
Set Object Name with Variable in VBA

Time:03-29

I am writing this code that initiates an object when a button is clicked.

Public Sub cmdMA_Click()

    Set this_renewal = CreateRenewal(this_renewal, cMA)
    
    Call BranchLabelVisibility(True)
    Me.Controls("lblBranchToAdd" & 1).Caption = this_renewal.Abb
    Call DateLabelVisibility(True)
    Me.Controls("lblYearToAdd" & 1).Caption = this_renewal.Year
    Me.Controls("lblMonthToAdd" & 1).Caption = this_renewal.Month
    Call TestMonth(1)

End Sub

However, certain buttons will need to run the same exact code on 2 objects like this:

Public Sub cmdAB_Click()

    Set this_renewal = CreateRenewal(this_renewal, cAB)
    
    Dim i As Integer: For i = 1 To 2
        Call BranchLabelVisibility(True)
        Me.Controls("lblBranchToAdd" & i).Caption = this_renewal.Abb
        Call DateLabelVisibility(True)
        Me.Controls("lblYearToAdd" & i).Caption = this_renewal.Year
        Me.Controls("lblMonthToAdd" & i).Caption = this_renewal.Month
        Call TestMonth(i)
    Next i

End Sub

I figured out how to do this with the controls, but I cannot figure out how to do this with my user defined class Renewal. I want to change it to something like this:

set Renewal("this_renewal" & i) = CreateRenewal(Renewal("this_renewal" & i))

Is there a way to do something like this? And then later I can call the object similarly.

CodePudding user response:

I would use an array of Renewal objects.

Dim Renewals(1) As Renewal
Set Renewals(0) = CreateRenewal(this_renewal, cMA)
Set Renewals(1) = CreateRenewal(this_renewal, cAB)

' Usage:
Me.Controls("lblBranchToAdd" & i).Caption = Renewals(i - 1).Abb

NOTE: There is a lot of code missing in your example. Not sure where this_renewal comes from. My example is not going to "just work" but it shows you the pattern you would use.

  • Related