Commandbutton captions

A

Al

I have a Userform that is initiated by user selection of certain cells, and I
need to display a number of CommandButtons corresponding to the length of a
list associated with the user selection. My form has the maximum number of
buttons I ever expect, and a macro sizes it to display only those needed.
I’m looking for a simple loop to add captions from the list, but I don’t see
any way to index the button reference in a loop. What I’m trying to do:

For n = 1 to List Count
CommandButtonn.Caption = Range(“Listâ€).Offset( n, 0)
Next

Obviously that won’t work, so I seem to be headed for a brute force method.
Is there a more elegant way?
 
P

Per Jessen

Hi

Assuming the CommandButtons is named "CommandButton1", "CommandButton2"....

Try this code

For n = 1 To ListCount
For Each c In Me.Controls
If c.Name = "CommandButton" & n Then
c.Caption = Range("List").Offset(n, 0).Value
Exit For
End If
Next
Next

Regards,
Per
 
R

Rick Rothstein \(MVP - VB\)

Try it this way...

Private Sub UserForm_Initialize()
Dim N As Long
For N = 1 To Range("List").Count
Me.Controls("CommandButton" & N).Caption = _
Range("List").Cells(N, 1).Value
Next
End Sub

Rick
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top