0

I want to iterate over the command buttons and replace the command button captions with the current i value. Each command button is named D plus a number (D1, D2, D3, D4, D5). I tried to use

    With Sheet1
      For i = 1 To 5
        Controls("D" & (i)).Caption = i
      Next 
    End With

But I get a compile error: Sub or function not defined.

The sub I am writing is contained in module1 and the command buttons are placed directly in Sheet1 with ActiveX command buttons (Microsoft Forms 2.0 Command Button). I have used the line: Controls("D" & (i)).Caption before with a form with no issues but I don’t want to use a form for this project. Is there a way to concatenate a letter and a variable in a for loop to match the names of the command buttons created and the current number being set to the caption of that button?

ELI
  • 1
  • This doesn't have a loop, but is the same general idea: https://stackoverflow.com/questions/10638620/reference-to-command-buttons-added-during-runtime-with-vba-in-excel – Warcupine Dec 23 '20 at 16:11
  • 2
    Worksheets do not have a `Controls` property. But if they did, to make your code work it would need to be `.Controls` (the leading period binds the `Controls` to the `With` block object) – Tim Williams Dec 23 '20 at 18:17

0 Answers0