so I tried to create a code just to do some basic formatting in the headers of long data sets. I have a fixsymbol code to change the um to micrometers with the proper symbol but when I try to run the code below to change the (um2) to a superscript 2 it flashes Error 13 type mismatch and the debug highlights this line "Position = InStr(c.Value, "µm2")" It still runs the code but spits the error at the end and if I try to run it on a raw data set not in a table it crashes Excel. How would I fix this error so I can have it run as a part of a larger script without crashing?
Sub ChangeToSuperScript()
Dim X As Long
Dim Position As Long
Dim c As Range
For Each c In Range("A:Z") 'range of cells
Position = InStr(c.Value, "µm2") 'change the number 2 into a potentiation sign
If Position Then c.Characters(Position + 2, 1).Font.Superscript = True
Next
End Sub
Thanks!
You can screen out error values.
EDIT: updated to use SpecialCells
to only operate on fixed values...
Sub ChangeToSuperScript()
Dim ws As Worksheet, rng As Range
Dim Position As Long, c As Range
Set ws = ActiveSheet
On Error Resume Next 'ignore error if no constants
Set rng = ws.Cells.SpecialCells(xlCellTypeConstants)
On Error GoTo 0 'stop ignoring errors
If rng Is Nothing Then Exit Sub 'no fixed values
On Error GoTo haveError
Application.Calculation = xlCalculationManual
For Each c In rng.Cells
Position = InStr(c.Value, "µm2")
Debug.Print c.Address, c.Value, Position
If Position > 0 Then
c.Characters(Position + 2, 1).Font.Superscript = True
End If
Next
Application.Calculation = xlCalculationAutomatic
Exit Sub
haveError:
Debug.Print "Error:" & Err.Description
Application.Calculation = xlCalculationAutomatic
End Sub