excel - 用于将 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
谢谢!
解决方案
您可以筛选出错误值。
编辑:更新为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
推荐阅读
- javascript - 在 Firebase 中订购实时更新
- wpf - 标签内容的 WPF 转换器
- docker - 将所有服务端口转发到单个容器
- android - 如何在不解码的情况下在画布上绘制压缩图像?
- driver - SV:程序驱动程序的错误合法组合
- php - 问题:从同一本地网络中的 Mac 登录本地服务器上的 mariadb 数据库
- python - 需要在前端的数据库中使用 Python 和 Selenium 停用用户,但参考过时
- java - 无法通过双击打开可执行 Jar 文件
- angular - 如何在 Angular 中检测 mat-stepper 的开始和结束?
- xml - XML - 如何决定是否将相同的节点放在父节点中