有没有办法更改Excel工作表中所有单元格中文本的颜色? 类似于查找文本并仅为Excel工作表的单元格更改搜索文本的前景色。
答案 0 :(得分:1)
举个例子:
Home
标签上选择Conditional Formatting
New Rule...
Use a formula to determine which cells to format
Format cells where this value is true
下输入公式:
=(LEN($ A $ 1)大于0)Format
,然后转到Fill
标签现在,如果单元格A1中有任何值,则步骤1中选择的整个范围将改变颜色。 您可以根据需要指定不同的单元格范围,条件或格式。 (例如,文本颜色而不是填充颜色)
回复:查找&替换以更改单元格的部分的颜色
查找&替换可以搜索或替换单元格格式,但替换格式会影响整个单元格。
结果:(整个细胞发生变化)
你说"没有VBA"但是为了分享可能的替代解决方案,以下是如何使用VBA实现这一点。此方法遍历ActiveSheet.UsedRange
:
Sub SearchReplace_Color_PartialCell()
Const textToChange = "cat"
Const newColor = vbRed
Dim c As Range
'loop throgh all cells that have data
For Each c In ActiveSheet.UsedRange.Cells
If InStr(c.Value, textToChange) > 0 Then 'if text exists in cell
' then change the color of that text
c.Characters(InStr(c.Value, textToChange), Len(textToChange)).Font.Color = newColor
End If
Next c
End Sub
当在10000个单元格上运行时,每个单元格都有不同长度的字符串,所有单元格都包含#34; cat"在中间,此方法以 2.6797秒运行。
另一个VBA解决方案,使用.Find
和.FindNext
循环访问包含数据的单元格:
Sub FindReplace_Color_PartialCell()
Const textToChange = "cat"
Const newColor = vbRed
Dim c As Range, firstAddress As String
With ActiveSheet.Cells
Set c = .Find(textToChange, LookIn:=xlValues)
If Not c Is Nothing Then
firstAddress = c.Address
Do
c.Characters(InStr(c.Value, textToChange), Len(textToChange)).Font.Color = vbGreen
Set c = .FindNext(c)
If c Is Nothing Then
GoTo DoneFinding
End If
Loop While c.Address <> firstAddress
End If
DoneFinding:
End With
End Sub
当在10000个单元格上运行时,每个单元格都有不同长度的字符串,所有单词都包含#34; cat&#34;在中间,此方法以 8.7021秒运行。
修改为继续搜索单元格,直到找不到进一步的匹配(而不是在一次替换后移动到下一个单元格):
Sub SearchReplace_Color_PartialCell()
'modified to catch multiple occurences of search term within the single cell
Const textToChange = "cat"
Const newColor = vbGreen
Dim c As Range 'the cell we're looking at
Dim pos As Integer 'current position#, where we're looking in the cell (0 = Not Found)
Dim matches As Integer 'count number of replacements
For Each c In ActiveSheet.UsedRange.Cells 'loop throgh all cells that have data
pos = 1
Do While InStr(pos, c.Value, textToChange) > 0 'loop until no match in cell
matches = matches + 1
pos = InStr(pos, c.Value, textToChange)
c.Characters(InStr(pos, c.Value, textToChange), Len(textToChange)).Font.Color = _
newColor ' change the color of the text in that position
pos = pos + 1 'check again, starting 1 letter to the right
Loop
Next c
MsgBox "Replaced " & matches & " occurences of """ & textToChange & """"
End Sub