VBA 用于在定义的字符串中将 2 更改为上标

问题描述

所以我试图创建一个代码只是为了在长数据集的标题中做一些基本的格式化。我有一个 fixsymbol 代码,可以使用正确的符号将 um 更改为微米,但是当我尝试运行下面的代码将 (um2) 更改为上标 2 时,它会闪烁错误 13 类型不匹配,并且调试突出显示了这一行“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

谢谢!

解决方法

您可以筛选出错误值。

编辑:更新为使用 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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...