Часть текста, выделенная жирным шрифтом после / перед специальным символом в ячейке - PullRequest
0 голосов
/ 01 апреля 2020

После ответа на поставленный выше вопрос и поиска дальнейших улучшений, есть ли способ полужирный текст c («повышение цены») и символы между этим текстом и специальным символом («~») , а затем получить ожидаемые результаты?

Ожидаемые результаты:

После повышение цены на ~ 0,1% против других в 2020 году:

После ~ 6% - повышение цены на 7% против других в 2019 году:

Sub Colors()

    Dim searchTerms As Variant

    searchTerms = Array("price increase")

    Dim searchString As String
    Dim targetString As String
    Dim offSet As Integer
    Dim colToSearch As Integer
    Dim arrayPos, rowNum As Integer

    colToSearch = 6

    For arrayPos = LBound(searchTerms) To UBound(searchTerms)
        For rowNum = 8 To 15

            searchString = Trim(searchTerms(arrayPos))

            offSet = 1

            Dim x As Integer

            If (Not IsError(Cells(rowNum, colToSearch).Value)) Then
            targetString = Cells(rowNum, colToSearch).Value

            x = HilightString(offSet, searchString, rowNum, colToSearch)
            End If

        Next rowNum
    Next arrayPos

End Sub

Function HilightString(offSet As Integer, searchString As String, rowNum As Integer, ingredCol As Integer) As Integer
            Dim x As Integer
            Dim newOffset As Integer
            Dim targetString As String

            ' offSet starts at 1

            targetString = Mid(Cells(rowNum, ingredCol), offSet)

            foundPos = InStr(LCase(targetString), searchString)

            If foundPos > 0 Then

                ' the found position will cause a highlight where it was found in the cell starting at the offset - 1

                Cells(rowNum, ingredCol).Characters(offSet + foundPos - 1, Len(searchString)).Font.Bold= True

                ' increment the offset to found position + 1 + the length of the search string
                newOffset = offSet + foundPos + Len(searchString)

                x = HilightString(newOffset, searchString, rowNum, ingredCol)
            Else
                ' if it's not found, come back out of the recursive call stack
                Exit Function
            End If
End Function

См. Это: Как выделить выделенный текст в Excel

1 Ответ

1 голос
/ 01 апреля 2020

Я рекомендую решить эту проблему с помощью регулярных выражений (см. Как использовать регулярные выражения (Regex) в Microsoft Excel как внутри ячейки, так и в циклах ).

В качестве примера вы можете использовать шаблон типа (~[0-9.% ]+.* )?price increase(.*~[0-9.%]+)?, чтобы найти текст, который нужно выделить.

enter image description here См. https://regex101.com/r/Un2O0e/1

...