I often find chemical formulae in my documents that require the numbers to be made subscript. e.g. H2O should be H2O and H2SO4 should be H2SO4. I am trying to write a macro that will take numbers from a highlighted selection and subscript numerical values. I am not very good at programming. I have tried variations on the following:
Sub SubscriptNumbers()
Dim Char As String
For Each Char In Selection.Characters
If Char >= "0" And Char <= "9" Then
Char = Char.Font.Subscript
End If
Next Char
End Sub
But I get confusing errors (Compile Error: For Each control variable must be Variant or Object
; but if I change Char to variant, it runs without error but doesn't appear to do anything). I know that there is an aversion from people in the know about using 'Select' but my doc will likely contain lots of other numbers that should not be made subscript.
Although not stated in the documentation to loop through Characters
you need to declare Char As Range
. You then need to check if Char.Text
is a number. There is a built-in function for doing this - IsNumeric
. Finally you need to set .Font.Subscript
to either true or false.
Sub SubscriptNumbers()
Dim Char As Range
For Each Char In Selection.Characters
If IsNumeric(Char.Text) Then
Char.Font.Subscript = True
End If
Next Char
End Sub