How to add VBA label values?

I'm just a beginner in using VBA in MS Excel. I have 1 form and 5 labels. Let's just name it Label1 to Label5. I want to have the sum of values of Label1 to Label4 and display it on Label5.

With UserForm1

   Dim str As String
   str = Label5.Caption
   str = WorksheetFunction.Sum(.Label1.Caption, .Label2.Caption, _
         .Label3.Caption, .Label4.Caption)
End With

This is the code that I got but it doesn't work. Please help T_T

Upvotes: 0

Views: 3368

Answers (2)

Thryn
Thryn

Reputation: 455

I would use

.Label5.caption = Cdec(.Label1.Caption) + Cdec(.Label2.Caption) + Cdec(.Label3.Caption) + Cdec(.Label4.Caption)

Upvotes: 0

Pᴇʜ
Pᴇʜ

Reputation: 57683

It didn't work because you put the result of Sum into str but not into Label5.

Note that a String variable is not an object but just a string value. So it does not reference to Label5.Caption instead str = Label5.Caption just copies the value of Label5.Caption into the variable str (no referencing).

With UserForm1
   .Label5.Caption = WorksheetFunction.Sum(.Label1.Caption, .Label2.Caption, .Label3.Caption, .Label4.Caption)
End With

Upvotes: 1

Related Questions