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

Net*_*eta 1 excel vba excel-vba

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
Run Code Online (Sandbox Code Playgroud)

上面的函数在'mouseover'一个单元格上调用,它设法将正确的单元格设置为RED颜色,但不会使文本变为粗体

Sco*_*ner 5

您无法从工作表中调用函数并更改单元格的格式.

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

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

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
Run Code Online (Sandbox Code Playgroud)

使用Worksheet_Change事件(或其他一些事件)来调用sub:

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
Run Code Online (Sandbox Code Playgroud)

将这两个放在您希望代码运行的工作表代码中.

现在,当您单击范围中的任何单元格时,这将突出显示相似的单元格.

在此输入图像描述