Home » excel » string – Trying to write power of (small numbers) with VBA code

string – Trying to write power of (small numbers) with VBA code

Posted by: admin May 14, 2020 Leave a comment

Questions:

I can’t figure out how to write power of to cells in Excel. I can use chr(185),chr(178) and chr(179) to display the power of 1,2 and 3 but I can’t do any other number.

How to&Answers:

You have 2 choices:

  1. using unicode characters
  2. using cell formatting

I think the formatting method is to be preferred for normal use because it is pretty flexible (e.g. easy to superscript a whole algebraic expression like x^(n-1)).

However, if you are ultimately exporting to a CSV or some other format then Excel formatting will not carry over, in which case you should use method 1. In addition, using this method allows the superscript characters to be passed around in formulae, compared to actual cell formatting that cannot be.

Using Unicode characters

Use the ChrW(charcode) function.

charcode can be the decimal or hexadecimal number for the unicode character.

The characters are:

SuperscriptHex        Dec        
0          2070       8304       
1          00B9       185        
2          00B2       178        
3          00B3       179        
4          2074       8308       
5          2075       8309       
6          2076       8310       
7          2077       8311       
8          2078       8312       
9          2079       8313    

(reference to unicode table: http://en.wikipedia.org/wiki/Unicode_subscripts_and_superscripts)

You can use &H as a literal indicating the chars that follow should be interpreted as hexadecimal, like ChrW(&H2077).

Using cell formatting

A Range object has a Characters property that returns a Characters object that allows different Font objects to different parts of the string. Normally, Range.Font is applied to the whole text.

Note that Font also has lots of other properties you can apply against the substring, like bold/size etc.

Examples:

'Method 1 - Unicode
ActiveCell.Value = "x" & ChrW(&H2079)

'Method 2 - Formatting
With ActiveCell.Offset(1, 0)
    .Value = "x9"
    .Characters(2, 1).Font.Superscript = True '2,1 is a substring from 2nd char for 1 char
End With