首页 > 解决方案 > 用于将 2 更改为上标的 VBA(当它位于已定义的字符串中时)

问题描述

所以我试图创建一个代码,只是为了在长数据集的标题中做一些基本的格式化。我有一个 fixsymbol 代码,可以使用正确的符号将 um 更改为微米,但是当我尝试运行下面的代码将 (um2) 更改为上标 2 时,它会闪烁 Error 13 type mismatch 并且调试会突出显示这一行“Position = InStr (c.Value, "µm2")" 它仍然运行代码,但在最后吐出错误,如果我尝试在原始数据集上运行它而不是在表中它会使 Excel 崩溃。我将如何修复此错误,以便我可以让它作为更大脚本的一部分运行而不会崩溃?

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

谢谢!

标签: excelvbasuperscriptdataformat

解决方案


您可以筛选出错误值。

编辑:更新为SpecialCells仅对固定值进行操作...

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


推荐阅读