Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
257 views
in Technique[技术] by (71.8m points)

excel - Adding thousand-separators and apostrophe to a number won't show the separators unless i remove the apostrophe?

I'm working on a macro to add separators and an apostrophe at the beginning of a number:

Sub Apostrofe()
Selection.NumberFormat = "#,##0"
For Each cell In Selection
    cell.Value = "'" & cell.Value
    Next cell
End Sub

Output for 123456789 is 123.456.789 but when it adds the apostrophe at the beginning, the format is lost. On the formula bar i see '123456789 but the separators won't appear unless i remove the apostrophe from the number.

I tried to concat the number in parts while manually adding the ' and . but the result is the same. Adding the apostrophe in the Format of the code added it on the cell but it wouldn't appear on the formula bar.

If i manually write the apostrophe + number with separators it works but i receive hundreds of numbers which must be formatted this way.

How can i modify the macro to do what i need?

question from:https://stackoverflow.com/questions/66053359/adding-thousand-separators-and-apostrophe-to-a-number-wont-show-the-separators

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you use an apostrophe the value will be converted to text.

It seems that in your example you do not change the value itself (to the text equivalent containing the formated number), you just apply the format to the cell and then overwrite it with '.

I think you should try following code:

cell.NumberFormat = "@"    ' set cell format to text
cell.Value = Format(cell.Value, "#,##0")    ' Format() returns formated number as a string

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...