3

This question arose in my attempt to answer this question:

In a blank workbook, format A1:A2 as text. In A1 type 123 and in A2 type '123. Both result in the string "123" being the cell value:

enter image description here

But -- the formula bar displays the text '123 when A2 is selected but only displays 123 when A1 is selected, so Excel retains the information about how the strings were entered. Can this information be accessed from VBA?

A quick test which shows what doesn't work:

Sub test()
    Dim R As Range, S As Range
    Set R = Range("A1")
    Set S = Range("A2")
    Debug.Print R.Value = S.Value
    Debug.Print R.Value2 = S.Value2
    Debug.Print R.Text = S.Text
    Debug.Print R.Formula = S.Formula
    Debug.Print R.FormulaLocal = S.FormulaLocal
    Debug.Print R.FormulaR1C1 = S.FormulaR1C1
    Debug.Print R.FormulaR1C1Local = S.FormulaR1C1Local
End Sub 

This does nothing but repeatedly print True. I can't think of any other range properties that would be relevant. I don't see any application or worksheet level object which allows one to access the text displayed in the formula bar. Any ideas?

2 Answers 2

6

You can use the PrefixCharacter property of Range to access the apostrophe.

Debug.Print [A1].PrefixCharacter ' prints blank line
Debug.Print [A2].PrefixCharacter ' prints apostrophe
1
  • That was easy. I attempted to use the Characters property but couldn't successfully call it on those cells (since those strings don't support RTF?) so I overlooked the other properties involving characters. I'll accept this when the requisite time has elapsed. Thanks. Commented Jan 24, 2018 at 13:44
2

Consider:

Sub SingleQuoteTest()
    MsgBox ActiveCell.PrefixCharacter = "'"
End Sub

enter image description here

3
  • Good answer (+1) but the other answer was first by about 10 seconds. There is still a potentially interesting question about how to programmatically access the displayed string in the formula bar. Commented Jan 24, 2018 at 13:51
  • @JohnColeman I have never attempted to get the Formula Bar as a text string. Commented Jan 24, 2018 at 13:55
  • It was actually your comment to this question that got me wondering about that: stackoverflow.com/q/41596316/4996248 Commented Jan 24, 2018 at 14:04

Not the answer you're looking for? Browse other questions tagged or ask your own question.