【问题标题】:VBA Macro to find specific text within cell range and style it boldVBA宏在单元格范围内查找特定文本并将其设置为粗体
【发布时间】:2017-10-31 15:16:34
【问题描述】:

我正在尝试开发一个宏来在工作簿内的所有工作表中查找特定文本并将文本设置为粗体。

这是我目前的工作正常:

Sub Style_Worksheets()

Dim ws As Worksheet

For Each ws In Sheets
    ws.Activate

Dim sCellVal As String

sCellVal = Range("A1").Value
sCellVal = Range("A5").Value
sCellVal = Range("A7").Value
sCellVal = Range("B7").Value

If sCellVal Like "*Workflow Name:*" Or _
sCellVal Like "Events*" Or _
sCellVal Like "Event Name*" Or _
sCellVal Like "Tag File*" Then

Range("A1").Font.Bold = True
Range("A5").Font.Bold = True
Range("A7").Font.Bold = True
Range("B7").Font.Bold = True

End If
Next ws
End Sub

现在我目前面临的问题是我有特定文本,在一个工作表中位于单元格 A16 中,但在另一个工作表中位于 A10 中。

我有 100 多个需要样式的工作表,每个工作表的特定文本位于不同的单元格中。

我希望宏在单元格 A10 和 A16 之间查找特定文本,如果找到文本,我希望它设置为粗体。

我已尝试将以下内容添加到其相关位置:

sCellVal = Range("A10:A16").Value

和:

sCellVal Like "Workflow Level Mappings*" Or _

和:

Range("A10:A16").Font.Bold = True

...但没有快乐。

谁能帮帮我?

谢谢,

一个

【问题讨论】:

  • 我建议查看 Find 方法,该方法将查找您指定的文本 - 如果您有几个替代文本位要查找,您似乎需要循环。

标签: vba excel


【解决方案1】:

试一试。全面测试。

Option Explicit

Sub Style_Worksheets()

    Dim TestPhrases() As String
    TestPhrases = Split("Workflow Name:,Events,Event Name,Tag File", ",")

    Dim ws As Worksheet

    For Each ws In Worksheets

        Dim CheckCell As Range
        For Each CheckCell In ws.Range("A10:A16")

            Dim Looper As Integer
            For Looper = LBound(TestPhrases) To UBound(TestPhrases)

                If InStr(CheckCell.Value, TestPhrases(Looper)) Then
                    CheckCell.Font.Bold = True
                    Exit For
                End If


            Next Looper

        Next CheckCell

    Next ws

End Sub

【讨论】:

  • 我认为你可以省略 >0。
  • 尽管根据代码,如果在同一单元格中找到所有项目,则范围内任何单元格中的文本都将是粗体。
  • @sktneer - 我确实调整了代码以使其工作。有趣的。我一直认为Instr 如果未找到则评估为 False,如果找到则评估为整数值。但如果找到,它也等同于 True。感谢您也提示 测试我自己的理论 :)
  • 通常人们将>0 与Instr 一起使用,看起来更合乎逻辑,但也可以不使用>0。很高兴你发现它有帮助。 :)
  • 您很好地编辑了代码,因为内部 for 循环中急需 Exit For。为此 +1。
【解决方案2】:

只需遍历有问题的单元格:

Sub Style_Worksheets()

    Dim ws As Worksheet, sCellVal As String
    Dim R As Range

    For Each ws In Sheets
        ws.Activate
        For Each R In Range("A1:A16")

            sCellVal = R.Text

            If sCellVal Like "*Workflow Name:*" Or _
                sCellVal Like "Events*" Or _
                sCellVal Like "Event Name*" Or _
                sCellVal Like "Tag File*" Then
                    R.Font.Bold = True
            End If
        Next R
    Next ws
End Sub

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-23
    • 1970-01-01
    • 1970-01-01
    • 2018-12-13
    • 1970-01-01
    • 1970-01-01
    • 2018-09-12
    • 1970-01-01
    相关资源
    最近更新 更多