excel - 单元格中的所有文本都使用相同的字体吗?

标签 excel vba

我正在处理一些 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/

相关文章:

excel - 我可以循环一系列非连续单元格,即 F35、F46、F54、F62...等

java - 从java,当一个实例中存在多个电子表格时,如何在关闭Excel电子表格时收到通知

excel - 过滤以仅显示在单元格中输入的日期之后的数据

excel - 使用 VBA 从外部工作簿添加工作表

VBA:未定义用户定义类型 MSXML2.DOMDocument60

excel - 将 Excel 中的频率表扩展为单列

arrays - 打乱数组,以便没有项目保留在同一位置

excel - 使用 VBA 检查日期是否在两个日期之间

vba - Excel VBA : Summing values in a row only when column heading meets a condition

vba - 将变量范围附加到数组vba