更改excel表格所有单元格的颜色:
举个例子:
- 选择整个工作表或单元格区域。
- 在
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 中选择的整个范围都会改变颜色。
您可以根据需要指定不同的单元格范围、条件或格式。 (例如,文本颜色而不是填充颜色)
编辑#1:
回复:查找和替换以更改单元格部分的颜色
查找和替换可以搜索或替换单元格格式,但替换格式会影响整个单元格。
结果:(整个单元格改变了)
编辑#2a:
您说“没有 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
当在 10,000 个单元格上运行时,每个单元格都有不同长度的字符串,中间都带有单词“cat”,此方法运行时间 2.6797 秒。
编辑#2b:
另一种 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
当在 10,000 个单元格上运行时,每个单元格都有不同长度的字符串,中间都带有单词“cat”,此方法运行时间 8.7021 秒。
编辑#2c:
修改为继续搜索一个单元格,直到找不到更多匹配项(而不是在一次替换后移动到下一个单元格):
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