Excel VBA函数使单元格文本“BOLD”不起作用

Public Function highlight_text(Search) Dim rng As Range Dim cell As Range Set rng = Range("A2:H32") For Each cell In rng If cell.text = Search Then cell.Font.ColorIndex = 3 cell.Font.Name = "Arial" cell.Font.Size = 14 cell.Font.Bold = True Else cell.Font.Bold = False cell.Font.Size = 11 cell.Font.ColorIndex = 1 End If Next cell End Function 

上面的函数是在“mouseover”单元格上调用的,它设法将适当的单元格设置为RED颜色,但不会使文本变成粗体

您不能从工作表调用函数并更改单元格的格式。

(甚至颜色变化的事实是令人困惑的)

因为这不需要是一个函数,它不会返回任何东西,你不能从工作表中使用它,我们可以使它成为一个子:

 Public Sub highlight_text(Search) Dim rng As Range Dim cell As Range Set rng = Range("A2:H32") For Each cell In rng If cell.Text = Search Then cell.Font.ColorIndex = 3 cell.Font.Name = "Arial" cell.Font.Size = 14 cell.Font.Bold = True Else cell.Font.Bold = False cell.Font.Size = 11 cell.Font.ColorIndex = 1 End If Next cell End Sub 

使用Worksheet_Change事件(或其他事件)来调用子:

 Private Sub Worksheet_SelectionChange(ByVal Target As Range) If Not Intersect(Target, Range("A2:H32")) Is Nothing Then highlight_text (Target.Text) End If End Sub 

把这两个这些工作表的代码,你想运行的代码。

当你点击范围内的任何单元格时,现在将突出显示类似的单元格。

在这里输入图像说明