我正在处理一些 Excel 文件,这些文件通常在单元格内包含大量文本。我想运行检查以确保所有文本都使用相同的字体(特别是 Calibri)。
目前我的做法是这样的。但它运行速度极慢。
Function fnCalibriCheck() As String
Dim CurrentCell As Range ' The current cell that is being checked
Dim SelectedRng As Range ' The selection range
Dim F As Long
Set SelectedRng = ActiveSheet.Range(Selection.Address) ' Defines the selection range
For Each CurrentCell In SelectedRng ' Goes through every cell in the selection and performs the check
For F = 1 To Len(CurrentCell)
If CurrentCell.Characters(F, 1).font.Name <> "Calibri" Then
fnCalibriCheck = "not calibri"
End If
Next
Next
End Function
该问题似乎特定于 Font.Name 属性。例如,如果我运行相同的代码,但我搜索特定字符而不是 Font.Name,那么它运行得很好。但事实上,我当前的宏可能需要几秒钟才能运行,并且偶尔会崩溃。
我想知道是否有人可以提出更好的替代方案。
最佳答案
您可以通过利用 Range
Font.Name
属性的以下行为来显着加快速度:
如果
范围
中所有个单元格的所有个字符具有相同的字体,则返回该字体名称如果
范围
中任何单元格的任何个字符与其他任何个单元格的字体不同任何其他单元格的字符,然后返回Null
这样你就可以简单地编码:
Function fnCalibriCheck() As String
If IsNull(Selection.Font.Name = "Calibri") Then fnCalibriCheck = "not Calibri"
End Function
您可以通过接受要扫描的范围和要检查的字体作为参数来使其更加通用
Function fnFontCheck(rng As Range, fontName As String) As String
If IsNull(rng.Font.Name = fontName) Then fnFontCheck = "not " & fontName
End Function
可以这样调用:
MsgBox fnFontCheck(Selection, "Calibri")
关于excel - 单元格中的所有文本都使用相同的字体吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42329151/