I'm using the COM interface to Excel and I would like to get hold of the formatted textual representation of a cell rather than the true underlying value.
For example, suppose the cell contains the number 1.23456
and the user has specified the number format with 1 decimal place. Then I'd like to be able to read the string "1.2"
. I know that I can use Range.Text
but this fails in a couple of significant ways. Range.Text
returns what the user sees in the view of the sheet and so if the cell is hidden then the empty string is returned. If the cell's width is low then a truncated string is returned. Range.Text
also falls down because it is limited to 1024 characters.
Another use case is when the cell evaluates to an error, e.g. #DIV/0!
, #NAME?
, #REF!
etc. I know that I can read Range.Value
and test if the variant is type varError
(I'm using Delphi, in VBA it would be vbError
). What I can't figure out is how to get hold of the text representation #DIV/0!
etc. Again Range.Text
returns this, but not if the cell is hidden or is too narrow.
EDIT
I think that the limit on Range.Text is actually 255 characters.
Thanks a lot Charles for your answer and helpful comments. I've now pieced together a Delphi/COM version of what I need which is as follows:
To get the text of a hidden cell that does not contain an error:
If it's an error, this fails. So you may want to first check:
Unfortunately, it's difficult to figure out what kind of error you have as the
Error.Type
function is not available from VBA or COM object. A work around for this would be to write that formula in another cell on the same sheet and read its value.Building on Steven's answer: try this VBA code.
It does not handle the Accounting format properly because of the lining-up requirement, but its not clear what you would want to do in that case anyway.