Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/vba/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Excel 如何搜索/替换术语(及其格式)?_Excel_Vba - Fatal编程技术网

Excel 如何搜索/替换术语(及其格式)?

Excel 如何搜索/替换术语(及其格式)?,excel,vba,Excel,Vba,我试图在工作簿中搜索各种术语,并将它们的格式更改为红色、粗体(本质上是突出显示术语)。我找到了下面的脚本,它只适用于一个学期。我一直在尝试添加附加条款,但没有成功。任何帮助都将不胜感激。提前谢谢 Sub colorText() Dim cl As Range Dim startPos As Integer Dim totalLen As Integer Dim searchText As String Dim endPos As Integer Dim testPos As Integer

我试图在工作簿中搜索各种术语,并将它们的格式更改为红色、粗体(本质上是突出显示术语)。我找到了下面的脚本,它只适用于一个学期。我一直在尝试添加附加条款,但没有成功。任何帮助都将不胜感激。提前谢谢

Sub colorText()

Dim cl As Range
Dim startPos As Integer
Dim totalLen As Integer
Dim searchText As String
Dim endPos As Integer
Dim testPos As Integer

' specify text to search.
 searchText = "Trust"

' loop trough all cells in selection/range
For Each cl In Selection

  totalLen = Len(searchText)
  startPos = InStr(cl, searchText) 
  testPos = 0

  Do While startPos > testPos
    With cl.Characters(startPos, totalLen).Font
      .FontStyle = "Bold"
      .ColorIndex = 3
    End With

    endPos = startPos + totalLen
    testPos = testPos + endPos
    startPos = InStr(testPos, cl, searchText, vbTextCompare)
  Loop

Next cl

End Sub

处理这个问题的一种方法是使用。删除
searchText
并将
ParamArray
参数添加到子系统:

Sub ColorText(ParamArray searchStrings() As Variant)
    Dim cl As Range
    Dim startPos As Integer
    Dim totalLen As Integer
    Dim endPos As Integer
    Dim testPos As Integer

    For Each searchItem In searchStrings
        For Each cl In Selection
            totalLen = Len(searchItem)
            startPos = InStr(cl, searchItem)
            testPos = 0

            Do While startPos > testPos
                With cl.Characters(startPos, totalLen).Font
                    .FontStyle = "Bold"
                    .ColorIndex = 3
                End With

                endPos = startPos + totalLen
                testPos = testPos + endPos
                startPos = InStr(testPos, cl, searchItem, vbTextCompare)
            Loop
        Next cl
    Next searchItem
End Sub
现在您可以调用另一个具有多个字符串的子/宏,如下所示:

Sub Test()
    ColorText "Trust", "Foo", "Bar"
End Sub
结果:


如果不想使用
ParamArray
或单独的方法(Sub),则可以在字符串数组上为每个循环运行

For Each searchItem In Array("Trust", "Foo", "Bar")
    ' Do your magic here.
Next searchItem

做得好。您还可以通过验证
searchStrings
是否只包含一个项,然后验证
IsArray(searchStrings(LBound(searchStrings)))
来组合这两种方法-在这两种情况下,建议使用
For…Next
循环,因为我们查看的是数组,而不是对象集合。