excel - 在 Excel 中,必须在单元格中搜索特定字符串并将样式应用于该特定字符串

标签 excel vba

在 Excel 中,我必须在单元格中搜索特定单词并仅替换该特定单词。

例如: 在 Excel 中,单元格可能包含

"team should have loaded test data into the file"

我只想选择此行中的一个单词,例如 test 并将样式应用于该特定字符串

"team should have loaded test data into the file"

我有很多单元格需要格式化,所以我想使用 VBA

最佳答案

这样的操作会将用户选择范围内的所有单元格中的“test”更改为粗体。它处理单个单元格中的多次出现

测试不区分大小写

Option Explicit

Const strText As String = "test"

Sub ColSearch_DelRows()
Dim rng1 As Range
Dim rng2 As Range
Dim cel1 As Range
Dim cel2 As Range
Dim strFirstAddress As String
Dim lAppCalc As Long
Dim objRegex As Object
Dim RegMC As Object
Dim RegM As Object

Set objRegex = CreateObject("vbscript.regexp")

With objRegex
    .Global = True
    .Pattern = strText
End With

'Get working range from user
On Error Resume Next
Set rng1 = Application.InputBox("Please select range to search for " & strText, "User range selection", Selection.Address(0, 0), , , , , 8)
On Error GoTo 0
If rng1 Is Nothing Then Exit Sub

With Application
    lAppCalc = .Calculation
    .ScreenUpdating = False
    .Calculation = xlCalculationManual
End With

Set cel1 = rng1.Find(strText, , xlValues, xlPart, xlByRows, , False)
If Not cel1 Is Nothing Then
    Set rng2 = cel1
    strFirstAddress = cel1.Address
    Do
        Set cel1 = rng1.FindNext(cel1)
        Set rng2 = Union(rng2, cel1)
    Loop While strFirstAddress <> cel1.Address
End If

If Not rng2 Is Nothing Then
    For Each cel2 In rng2
        Set RegMC = objRegex.Execute(cel2.Value)
        For Each RegM In RegMC
            cel2.Characters(RegM.firstindex, RegM.Length + 1).Font.Bold = True
        Next
    Next
End If

With Application
    .ScreenUpdating = True
    .Calculation = lAppCalc
End With

End Sub

关于excel - 在 Excel 中,必须在单元格中搜索特定字符串并将样式应用于该特定字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9717030/

相关文章:

excel - Outlook 发送事件类

VBA静态类 "WithEvents"?

vba - 如何优化一组解析字符串和变体类型的 VBA 函数

excel - VBA If/ElseIf-编译错误: Duplication in Current Scope

r - 从字符串中解析数据

VBA 代码中的 Excel 公式

python - 使用 python xlrd 从 Excel 单元格中获取公式

Excel公式获取季节名称?

vba - 在打开和关闭 application.screenupdating 时更新打开的 Excel 工作表上的单元格

vba - Outlook 2007 中的 ItemSend 事件中的密件抄送不再有效