2012年2月6日月曜日

[VBA] On Error Go To

Amazed the fact that VBA still holds "On Error GoTo" statement, which is unstructured and came from an ice age.
//http://excelvba.pc-users.net/fol6/6_8.html

Sub OnErrorTest()
    On Error GoTo ErrorTrap
    
    Dim i As Integer
    i = "test"             '
    
    MsgBox "Exit."
    
    Exit Sub

ErrorTrap:
    MsgBox "Error no.:" & Err.Number
    MsgBox "Description:" & Err.Description
    MsgBox "Help file" & Err.HelpContext
    MsgBox "Project:" & Err.Source
    Resume Next
End Sub
//

Now I feel how modern "try/catch" statement is sophisticated.

[VBA] Replace strings in cells without flushing format

When you replace a string within a formatted cell on Excel sheet using VBA, the format such as font/size/style is vanished.

I think this comes from any formatting within cells are hidden from VBA programmers.

To resolve the issue, you have to backup the formatted cell to other unused sheet temporarily and recover the format with the backup cell, by reading all the styles by characters, one bye one.
The concept is:
//
Function ReplaceInFormattedCells(TargetCell as variant, SearchStr as string, ReplaceStr as string)
Dim BackupCell as variant
BackupCell = TargetCell 'Implement here the backup procedure as you like
With TargetCell
            .Cells.Replace What:=InnerLF, Replacement:=vbLf, LookAt:=xlPart, MatchCase:=True, MatchByte:=True
            strLength = Len(TargetCell)
            For i = 1 To strLength Step 1
                .Characters(i, 1).Font.ColorIndex = BackupCell.Characters(i, 1).Font.ColorIndex
                .Characters(i, 1).Font.Color = BackupCell.Characters(i, 1).Font.Color
                '.Characters(i, 1).Font.Bold = BackupCell.Characters(i, 1).Font.Bold
                '.Characters(i, 1).Font.FontStyle = BackupCell.Characters(i, 1).Font.FontStyle
                '.Characters(i, 1).Font.Italic = BackupCell.Characters(i, 1).Font.Italic
                '.Characters(i, 1).Font.Size = BackupCell.Characters(i, 1).Font.Size
                '.Characters(i, 1).Font.Underline = BackupCell.Characters(i, 1).Font.Underline
                '.Characters(i, 1).Font.Shadow = BackupCell.Characters(i, 1).Font.Shadow
                '.Characters(i, 1).Font.Strikethrough = BackupCell.Characters(i, 1).Font.Strikethrough
                '.Characters(i, 1).Font.Subscript = BackupCell.Characters(i, 1).Font.Subscript
                '.Characters(i, 1).Font.Superscript = BackupCell.Characters(i, 1).Font.Superscript
            Next i
End With
//