excel - 使用Find方法格式化某个范围内的某些字符串

标签 excel vba

我有一个范围,其中包含字符串“freq!”的多个实例随机散布各处。我想将这些字符串的字体更改为红色。我尝试使用 Find 方法,但没有成功:

[D1:H5000].Find(What:=”freq!”, LookIn:=xlValues).Font.Color = RGB(255,0,0)

我哪里出错了?

最佳答案

您的 .Find 不起作用的原因是它仅设计用于查找一个实例。要查找多个实例,您还需要在循环中使用 .FindNext。请参阅下面的示例:

请注意搜索字符串周围通配符的使用。

Sub ChangeFontColor()

Dim rng As Range
Dim rr As Range
Dim sAdd As String
Dim sStr As String

sStr = "*freq!*"

With Worksheets("YourSheetName").Range("D1:H5000")
    Set rng = .Find(sStr)
    If Not rng Is Nothing Then
        sAdd = rng.Address
        Do
            If rr Is Nothing Then
                Set rr = rng
            Else
                Set rr = Application.Union(rr, rng)
            End If
            Set rng = .FindNext(rng)
        Loop While Not rng Is Nothing And rng.Address <> sAdd
    End If
End With

If Not rr Is Nothing Then
    rr.Font.Color = RGB(255,0,0)
End If

End Sub

这个示例应该执行得很快,具体取决于实例的数量。 See this有关 .FindNext 的更多信息。

关于excel - 使用Find方法格式化某个范围内的某些字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21565909/

相关文章:

vba - 使用 VBA 在单元格中分组

excel - 如何验证 2 个变量是整数类型?

excel - 使用VBA获取MDX数据

java - 雅各布 : calling vb function in Excel file without invoking "Open" statement

excel - 将所有 Excel 工作表设置为定义的缩放级别

VBA 使用数组值作为单元格验证值

Excel VBA 不会粘贴前导零

sql - 无法调试 MS Access 2013 运行时错误 91

excel - 在 Excel VBA 中删除一行

arrays - 使用范围填充数组)单元格