I'm new to VBA and trying to write a script that inserts XML tags around italicized text in Excel. I discovered this question: VBA Excel Changing Italics and adding </ and />
The first answer has a clever approach and I'm modifying that code. It works as is for the first italicized string in a cell, but not for subsequent strings.
Here is the code I'm trying. It loops through each character until it finds the first Italics and inserts a tag and turns the lngCount variable to True. When it finds regular text, if the lngCount variable is True, it inserts the end tag and resets the variable to False.
It works perfectly in some cells, but in other places it doesn't insert the end tag, it others it doesn't insert any tags. Since I can't figure out any consistent differences to when it works well and doesn't, can anyone help? Am I misunderstanding anything about vba?
Sub EmphTags()
Dim lngStart As Long
Dim lngFinish As Long
Dim n As Long
Dim rngCell As Range
Dim rngConstants As Range
On Error Resume Next
Set rngConstants = ActiveSheet.UsedRange.SpecialCells(xlCellTypeConstants)
On Error GoTo 0
If Not rngConstants Is Nothing Then
'Application.ScreenUpdating = False
For Each rngCell In rngConstants.Cells
lngCount = False
lngStart = 0
lngFinish = 0
For n = 1 To Len(rngCell.Text)
If rngCell.Characters(n, 1).Font.Color = 0 Then
If rngCell.Characters(n, 1).Font.Italic Then
If lngCount = False Then
lngStart = n
rngCell.Characters(lngStart, 0).Insert "<emph render='italic'>"
rngCell.Characters(lngStart, 22).Font.Italic = True
End If
lngCount = True
ElseIf lngCount = True Then
lngFinish = n
rngCell.Characters(lngFinish, 0).Insert "</emph>"
rngCell.Characters(lngFinish, 7).Font.Italic = False
lngCount = 0
End If
End If
Next n
Next rngCell
'Application.ScreenUpdating = True
End If
End Sub
No comments:
Post a Comment