Welcome to OStack Knowledge Sharing 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 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...