excel - 如何查找单元格的一部分并将其替换为格式化文本

标签 excel excel-2007 vba

在 Excel 2007 电子表格中,我想要查找替换并突出显示单元格中的部分文本。不过,使用查找替换会重新格式化整个单元格。

例如,如果单元格包含:

Pellentesque vel massa sit amet magna eleifend placerat. Pellentesque dictum, nibh vitae tincidunt placerat, elit libero tristique tellus, vel imperdiet nulla tortor id diam. Mauris porta blandit vestibulum.

我想找到“Pellentesque”并将其替换为Pellentesque

这可以在没有 VBE 或公式的情况下完成吗?

最佳答案

也许这适合(请确保在运行之前选择的单元格数量不超过所需的数量,否则可能需要一段时间):

Sub FormatSelection()

Dim cl As Range
Dim SearchText As String
Dim StartPos As Integer
Dim EndPos As Integer
Dim TestPos As Integer
Dim TotalLen As Integer

On Error Resume Next
Application.DisplayAlerts = False
SearchText = Application.InputBox _
(Prompt:="Enter string.", Title:="Which string to format?", Type:=2)
On Error GoTo 0
Application.DisplayAlerts = True
If SearchText = "" Then
Exit Sub
Else
For Each cl In Selection
  TotalLen = Len(SearchText)
  StartPos = InStr(cl, SearchText)
  TestPos = 0
  Do While StartPos > TestPos
    With cl.Characters(StartPos, TotalLen).Font
      .FontStyle = "Bold"
      .ColorIndex = 3
    End With
    EndPos = StartPos + TotalLen
    TestPos = TestPos + EndPos
    StartPos = InStr(TestPos, cl, SearchText, vbTextCompare)
  Loop
Next cl
End If
End Sub

应该鼓励并涂上红色。如果重新运行宏,更改不会被覆盖。如果不改变颜色,注释掉.ColorIndex = 3。

(基于 @Skip Intro 指向 SO15438731 问题的指针并进行了修改,以及 SO10455366 答案中的一些代码。)

关于excel - 如何查找单元格的一部分并将其替换为格式化文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16964251/

相关文章:

VBA 向表中插入一行,格式如下

excel - 内存不足,无法继续执行程序。从 CSV 创建 Xlsx

excel - Excel 2007 VBA 中重叠范围的条件格式 - 错误?

ms-access - 循环遍历名称类似于示例的查询

excel - 在 Excel/VBA 中将日期和时间连接到单个单元格中

c# - 使用 com interop 从 VBA 调用 C# dll 时出现类型不匹配错误

excel - 表中比较条件

excel - 这条线是 VBA 中不必要的线吗?

Excel工作表中列中字符串模式匹配的VBA代码

vba - 将数据锁定到 Excel 图表