简体   繁体   中英

How to add comma to a number in the text in Excel VBA

I am working on a project that create report automatically according to inport values. In sheet2 I have input data like C10=1000 , C11=150000 and I want at the sheet1 as C4= 1,000.00 MWh and C5= 150,000 Dollar and I want the numbers as bold. I write a code like this:

Private Sub CommandButton1_Click()
Dim Range1, Range2
Set Range1 = ThisWorkbook.Sheets(2).Range("C10")
Set Range2 = ThisWorkbook.Sheets(2).Range("C11")
Application.EnableEvents = False
 ThisWorkbook.Sheets(1).Range("C4") = Range1.Value & " MWh"
 ThisWorkbook.Sheets(1).Range("C5") = Range2.Value &" Dollar"
 With ThisWorkbook.Sheets(1).Range("C4")
 .Characters(InStr(ThisWorkbook.Sheets(1).Range("C4").Value, Range1), Len(CStr(Range1))).Font.FontStyle = "Bold"
 End With
 With ThisWorkbook.Sheets(1).Range("C5")
 .Characters(InStr(ThisWorkbook.Sheets(1).Range("C5").Value, Range2), Len(CStr(Range2))).Font.FontStyle = "Bold"
 End With
Application.EnableEvents = True
ThisWorkbook.Sheets(1).Activate
End Sub

But I am getting the results correctly but I cant figure out how to add commas between the digits I tried .NumberFormat but It didn't work because it is not in the correct format.

Is there any way to do that?

You need to use

.NumberFormat = "#,##0.00 ""Mwh"""

and the value needs to be numeric

.Value = 1000

Then it will show like

1,000.00 Mwh

in your cell.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM