最近遇到一个需求,实验室的同事说经常要在Excel里输入各种化学式,化学式里有很多数字下标,但是在Excel里改下标需要一个一个改,太麻烦了。于是,我给写了一段VBA,一键批量将Excel所选单元格中的数字变为下标:
Sub 批量改下标()
Application.ScreenUpdating = True '禁用屏幕自动刷新,提高运行效率
Dim selectedRang As Range '所选单元格Range
Dim strLength As Integer '单元格内字符串长度
Dim i As Integer
For Each selectedRang In Selection
strLength = Len(selectedRang.Text)
For i = 1 To strLength
If IsNumeric(Mid(selectedRang.Text, i, 1)) = True Then '如果是数字,则执行下标变换
selectedRang.Characters(Start:=i, Length:=1).Font.Subscript = True
End If
Next
Next
Application.ScreenUpdating = True '恢复屏幕自动刷新,提高运行效率
End Sub
最后运行效果:
发表回复