gpt4 book ai didi

excel - 查找文本并更改颜色

转载 作者:行者123 更新时间:2023-12-04 22:30:04 27 4
gpt4 key购买 nike

我想循环工作簿的所有工作表,以更改其中包含特定字符串的单元格的颜色。
我用 .Replace (我需要 MatchCase 并查看)。
它在不考虑大小写的情况下替换文本。 (例如,如果在数组中它是小写的并且找到的字符串是大写的,它将被更改为小写)。绕过它的唯一方法是使用 MatchCase:= false并列出所有选项,它可能真的效率低下。
我可以使用 .Find 执行该操作吗?或其他功能?

Sub CellMarked()

Dim fndlist As Variant, x As Integer, sht as worksheet

fndlist = Array("Column1", "Column2")

For Each sht In ActiveWorkbook.Worksheets
With sht
For x = LBound(fndlist) To UBound(fndlist)
.Cells.Replace What:=fndlist(x), Replacement:=fndlist(x), _
lookat:=xlPart, SearchOrder:=xlByRows, MatchCase:=True, _
SearchFormat:=False, ReplaceFormat:=True
Application.ReplaceFormat.Font.Color = 255
Next x
End With
next sht

End Sub

最佳答案

你可以使用 Find()方法并构建一个辅助函数:

Function GetCellsWithValue(sht As Worksheet, val As Variant, foundCells As Range) As Boolean
Dim found As Range
Dim firstAddress As String
With sht.UsedRange
Set foundCells = .Resize(1, 1).Offset(.Rows.Count) ' fill foundCells with a "dummy" found one to avoid 'If Not foundCells Is Nothing' check before any 'Union()' method call

Set found = .Find(what:=val, lookat:=xlPart, LookIn:=xlValues)
If Not found Is Nothing Then
firstAddress = found.Address
Do
Set foundCells = Union(foundCells, found)
Set found = .FindNext(found)
Loop While found.Address <> firstAddress
End If

Set foundCells = Intersect(.Cells, foundCells) ' get rid of the "dummy" found cell
End With

GetCellsWithValue = Not foundCells Is Nothing
End Function

您可以在“主要”子中使用如下:
Option Explicit

Sub CellMarked()

Dim fndlist As Variant, val As Variant, sht As Worksheet
Dim foundCells As Range

fndlist = Array("Column1", "Column2")

For Each sht In ActiveWorkbook.Worksheets
With sht
For Each val In fndlist
If GetCellsWithValue(sht, val, foundCells) Then foundCells.Font.Color = 255
Next
End With
Next sht

End Sub

关于excel - 查找文本并更改颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53911422/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com