0

I'm using the code below to add a toggle button to sheet. I will need to dynamically re-create a sequence of buttons, and give them name and caption.

Can anyone help me with a way to change the caption/text of the toggle button button added using VBA? The bName will change so I will need a way to reference them by name.

Set Bttn = ActiveSheet.OLEObjects.Add(ClassType:="Forms.ToggleButton.1", Link:=False, _
                DisplayAsIcon:=False, Left:=R.Left, Top:=R.Top, Width:=R.Width, Height:=R.Height)
With Bttn
    .Name = bName
End With

where R is the target cell where button will be added

I tried the following, and they all error out:

Bttn.caption = bText
ActiveSheet.Shapes(bName).Text = bText
Dumitru Daniel
  • 571
  • 4
  • 19

2 Answers2

2

Or, simply . . .

With Bttn
    .Name = bName
    .Object.Caption = "MyCaption"
End With
Domenic
  • 7,844
  • 2
  • 9
  • 17
1

I found this workaround here: https://stackoverflow.com/a/37978572/9852011

Not sure why you need to do this exactly but this code should work for you:

Dim Bttn As OLEObject, aButton As Variant

Set Bttn = ActiveSheet.OLEObjects.Add(ClassType:="Forms.ToggleButton.1", Link:=False, _
                DisplayAsIcon:=False, Left:=R.Left, Top:=R.Top, Width:=R.Width, Height:=R.Height)
With Bttn
    .Name = bName
End With

Set aButton = Bttn.Object
aButton.Caption = "whateverYouWant"
andrewb
  • 1,129
  • 5
  • 9