在Excel中必须在单元格中search特定的string,并将样式应用于该特定的string

在Excel中,我必须search单元格中的特定单词,并仅replace特定的单词。

例如:在excel中可能包含一个单元格

“团队应该已经将testing数据加载到文件”

我想在这一行中只select一个单词,例如testing,并将样式应用于特定的string

“团队应该已经将testing数据加载到文件”

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

像这样的东西会将用户选定范围内的所有单元格中的“testing”更改为粗体。 它处理单个单元格中的多个事件

该testing是不区分大小写的

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 

下面是一段代码,向您展示如何格式化单元格中的一段文本:

 Sub EditFont() 'To format font color for 12 digits to 4 black, 5 red, 3 black: ' Here is some sample text to try it on: 123456789012 'First, format digits to be treated as characters ActiveCell.Value = "'" & ActiveCell.Value 'Format all characters for black With ActiveCell .Font.ColorIndex = 3 'Format characters 5 thru 12 as red .Characters(1, ActiveCell.Characters.Count - 8).Font.ColorIndex = 1 'Reformat characters 10 thru 12 back to black .Characters(10, ActiveCell.Characters.Count - 3).Font.ColorIndex = 1 End With End Sub 

你只需要在需要的单元格上添加一个循环。

[ 来源 ]