Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically update labels captions in VBA form?

Tags:

excel

label

vba

I want to dynamically set the caption for an array of labels (within a VBA form) based on values stored in a worksheet. Thus far I can set them one-by-one like this:

Label1.Caption = MySheet.Range("A1").Value
Label2.Caption = MySheet.Range("B1").Value
Label3.Caption = MySheet.Range("C1").Value ...

Having lots of labels that follow a recurrent pattern, I want to use something smarter, like:

'Method1
For i = 1 To X
    Dim MyLabel as Object: Set MyLabel = "Label" & i
    MyLabel.Caption = MySheet.Cells(i + 1, i).Value
Next i
'Method2
For i = 1 To X
    Label(i).Caption = MySheet.Cells(i + 1, i).Value
Next I
'Both Methods failed. I really appreciate some feedback on this.
like image 487
Takedasama Avatar asked Dec 19 '13 09:12

Takedasama


People also ask

How do I change the caption on a UserForm?

Run ShowForm . Click on the form. The caption is changed. Then change the activesheet and click on the form again.

How do I define a label in VBA?

In VBA a "line label" is defined by an identifier followed by a colon, at the beginning of a line of code (and ideally, sitting on its own line): LineLabel: "Label not defined" is the compile error you get when an instruction is referring to a label that doesn't exist in that scope.


2 Answers

If you want to use this in VBA:

For i = 1 To X
    UserForm1.Controls("Label" & i).Caption =  MySheet.Cells(i + 1, i).Value
Next
like image 88
Ahmet Toka Avatar answered Sep 30 '22 23:09

Ahmet Toka


Use Controls object

For i = 1 To X
    Controls("Label" & i).Caption =  MySheet.Cells(i + 1, i).Value
Next
like image 26
Siddharth Rout Avatar answered Sep 30 '22 21:09

Siddharth Rout