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
4.5k views
in Technique[技术] by (71.8m points)

excel - Return formatted value of cell and not ###### (Robust method)?

I am looking for a robust way to return the formatted/shown value of a cell. First a simply used the Cell.Text property but then I noticed a got errors when the cell was to small to fit. Then it only returns "########"

Here is a small example showing the problem. I want it to return 50.1000000 no matter how small the column is.

Sub Makro1()
' Desired action: Outputs text formatted value of activecell
'
    MsgBox "The value is """ & ActiveCell.Text & """"
End Sub

enter image description here

I have tried using something like this (using Format and the .Value and .NumberFormat properties) but I am unsure how robust it is. Is there a better way?

Sub Makro2()
' Desired action: Outputs text formatted value of activecell
'
    MsgBox "The value is """ & Format(ActiveCell.Value, ActiveCell.NumberFormat) & """"
End Sub

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

1 Reply

0 votes
by (71.8m points)

I think I found the right answer to my own question but I still would like to leave it open for other answers. I think the most robust way is to use the worksheetfunction text WorksheetFunction.Text and use the cell.NumberFormatLocal property. It seems to handle Numberformats like "general" that the VBA Format function doesn't accept.

Sub Makro4()
' Desired action: Outputs text formatted value of activecell
'
    MsgBox "The value is """ & WorksheetFunction.Text(ActiveCell.Value, ActiveCell.NumberFormatLocal) & """"
End Sub

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

...