Thursday, September 8, 2011

Format part of a found text string in a list of items

Extending the above procedure, you may wish to format a number of similar items - eg chemical formulae. The following version defines the list of items as variants. Note that the subscripted numbers are located in different parts of the text string. The macro loops through the list searching for each variant throughout the document in turn. It then uses Case statements to process the range for each variant to achieve the results shown in red (when pasted to the vba editor the red colour will change to green and the format of the red coloured items will be lost).
In the cases where there are two or digits to format, they are processed separately. You could adapt this technique to format any character in the search strings in any manner you require.



Sub FormatChemicalFormulae()
Dim rText As Range
Dim vFindText(4) As Variant 'match the number in the brackets
'to the last number in the list below
Dim i As Long

vFindText(0) = "H2O"
vFindText(1) = "CO2"
vFindText(2) = "H2SO4"
vFindText(3) = "SO42-"
vFindText(4) = "[CO(NH3)6]3+"
'add more numbers as required
'increment the number 'n' in the brackets vFindText(n)

For i = 0 To UBound(vFindText)
    With Selection
        .HomeKey wdStory
        With .Find
            .ClearFormatting
            .Replacement.ClearFormatting
            Do While .Execute(findText:=vFindText(i), _
                MatchWildcards:=
False, _
                Wrap:=wdFindStop, Forward:=
True) = True
                Set rText = Selection.Range 'The found text
                With rText 'Do what you want with the found text
                    Select Case i
                    Case Is
= 0 'H2O - H2O
                       
.Characters(2).Font.Subscript = True
                    Case Is
= 1 'CO2 - CO2
                       
.Characters(3).Font.Subscript = True
                    Case Is
= 2 'H2SO4 - H2SO4
                       
.Characters(2).Font.Subscript = True
                       
.Characters(5).Font.Subscript = True
                    Case Is
= 3 'SO42- - SO42-
                        
.Characters(3).Font.Subscript = True
                         .
Characters(4).Font.Superscript = True
                        
.Characters(5).Font.Superscript = True
                    Case Is
= 4 '[CO(NH3)6]3+ - [Co(NH3)6]3+
                        
.Characters(3).Case = wdLowerCase
                        
.Characters(7).Font.Subscript = True
                        
.Characters(9).Font.Subscript = True
                        
.Characters(11).Font.Superscript = True
                        
.Characters(12).Font.Superscript = True
                    End Select

                
End With
            Loop
'and look for the next match
        End With
    End Wit
h
Next i
End Sub

No comments:

Post a Comment