Ir para o conteúdo principal

Como colorir ou destacar determinada palavra nas células do Excel?

Se uma célula contém várias palavras, como você pode destacar uma determinada palavra apenas nesta célula? E que tal destacar essa determinada palavra em várias células? Este artigo fornecerá um método para alcançá-lo.

Pinte determinada palavra em uma única célula / células múltiplas com código VBA


Pinte determinada palavra em uma única célula / células múltiplas com código VBA

O código VBA a seguir pode ajudá-lo a destacar determinada palavra em uma seleção. Faça o seguinte.

1. Selecione o intervalo que contém as células nas quais deseja destacar uma determinada palavra. Em seguida, pressione o outro + F11 simultaneamente para abrir o Microsoft Visual Basic para Aplicações janela.

2. Na abertura Microsoft Visual Basic para Aplicações janela, clique em inserção > Módulo. Em seguida, copie e cole o código VBA na janela Código.

Código VBA: pinte certas palavras nas células do Excel

Sub HighlightStrings()
    Dim xHStr As String, xStrTmp As String
    Dim xHStrLen As Long, xCount As Long, I As Long
    Dim xCell As Range
    Dim xArr
    On Error Resume Next
    xHStr = Application.InputBox("What is the string to highlight:", "KuTools For Excel", , , , , , 2)
    If TypeName(xHStr) <> "String" Then Exit Sub
    Application.ScreenUpdating = False
        xHStrLen = Len(xHStr)
        For Each xCell In Selection
            xArr = Split(xCell.Value, xHStr)
            xCount = UBound(xArr)
            If xCount > 0 Then
                xStrTmp = ""
                For I = 0 To xCount - 1
                    xStrTmp = xStrTmp & xArr(I)
                    xCell.Characters(Len(xStrTmp) + 1, xHStrLen).Font.ColorIndex = 3
                    xStrTmp = xStrTmp & xHStr
                Next
            End If
        Next
    Application.ScreenUpdating = True
End Sub

3. aperte o F5 chave para executar o código. E no Kutools for Excel caixa de diálogo, digite a palavra certa que você destacará nas células e clique no botão OK botão. Veja a imagem:

Então você pode ver que todas as palavras que você especificou estão coloridas em vermelho nas células selecionadas imediatamente, conforme mostrado na imagem abaixo.


Artigos relacionados:

Melhores ferramentas de produtividade de escritório

🤖 Assistente de IA do Kutools: Revolucionar a análise de dados com base em: Execução Inteligente   |  Gerar Código  |  Crie fórmulas personalizadas  |  Analise dados e gere gráficos  |  Invocar funções do Kutools...
Recursos mais comuns: Encontre, destaque ou identifique duplicatas   |  Excluir linhas em branco   |  Combine colunas ou células sem perder dados   |   Rodada sem Fórmula ...
Super pesquisa: VLookup de múltiplos critérios    VLookup de múltiplos valores  |   VLookup em várias planilhas   |   Pesquisa Difusa ....
Lista suspensa avançada: Crie rapidamente uma lista suspensa   |  Lista suspensa de dependentes   |  Lista suspensa de seleção múltipla ....
Gerenciador de colunas: Adicione um número específico de colunas  |  Mover colunas  |  Alternar status de visibilidade de colunas ocultas  |  Compare intervalos e colunas ...
Recursos em destaque: Foco da Grade   |  Vista de Design   |   Grande Barra de Fórmula    Gerenciador de pastas de trabalho e planilhas   |  Biblioteca (Auto texto)   |  Data Picker   |  Combinar planilhas   |  Criptografar/Descriptografar Células    Enviar e-mails por lista   |  Super Filtro   |   Filtro Especial (filtro negrito/itálico/tachado...) ...
15 principais conjuntos de ferramentas12 Texto Ferramentas (Adicionar texto, Remover Personagens, ...)   |   50+ de cores Tipos (Gráfico de Gantt, ...)   |   Mais de 40 práticos Fórmulas (Calcule a idade com base no aniversário, ...)   |   19 Inclusão Ferramentas (Insira o código QR, Inserir imagem do caminho, ...)   |   12 Conversão Ferramentas (Números para Palavras, Conversão de moedas, ...)   |   7 Unir e dividir Ferramentas (Combinar linhas avançadas, Dividir células, ...)   |   ... e mais

Aprimore suas habilidades de Excel com o Kutools para Excel e experimente uma eficiência como nunca antes. Kutools para Excel oferece mais de 300 recursos avançados para aumentar a produtividade e economizar tempo.  Clique aqui para obter o recurso que você mais precisa...

Descrição


Office Tab traz interface com guias para o Office e torna seu trabalho muito mais fácil

  • Habilite a edição e leitura com guias em Word, Excel, PowerPoint, Publisher, Access, Visio e Project.
  • Abra e crie vários documentos em novas guias da mesma janela, em vez de em novas janelas.
  • Aumenta sua produtividade em 50% e reduz centenas de cliques do mouse para você todos os dias!
Comments (24)
Rated 5 out of 5 · 1 ratings
This comment was minimized by the moderator on the site
Is there any chance that I can do both coloring and make words Bond with that VBA code? Please help me :)
This comment was minimized by the moderator on the site
Bonjour Cristal,
Merci pour ce code. Est-il possible de l'adapter pour mettre en évidence plusieurs mots "Apple,Rose,Vert,Merci"
Merci
This comment was minimized by the moderator on the site
Hi Cous,

The following VBA code can help. After running the code, you will get a dialog box. Please type in the words you want to highlight and separate them by comma.
https://www.extendoffice.com/images/stories/comments/comment-picture-zxm/highlight.png
Sub HighlightStrings()
'Updated by Extendoffice 20230130
    Dim xHStr As String, xStrTmp As String
    Dim xHStrLen As Long, xCount As Long, I As Long
    Dim xCell As Range
    Dim xArr
    Dim xArr2
    On Error Resume Next
    xHStr = Application.InputBox("What is the string to highlight:", "KuTools For Excel", , , , , , 2)
    If TypeName(xHStr) <> "String" Then Exit Sub
    Application.ScreenUpdating = False
    
    xArr2 = Split(xHStr, ",")
    For j = 0 To UBound(xArr2)
        xHStr = xArr2(j)
    
        xHStrLen = Len(xHStr)
        For Each xCell In Selection
            xArr = Split(xCell.Value, xHStr)
            xCount = UBound(xArr)
            If xCount > 0 Then
                xStrTmp = ""
                For I = 0 To xCount - 1
                    xStrTmp = xStrTmp & xArr(I)
                    xCell.Characters(Len(xStrTmp) + 1, xHStrLen).Font.ColorIndex = 3
                    xStrTmp = xStrTmp & xHStr
                Next
            End If
        Next
    Next
    
    Application.ScreenUpdating = True
End Sub
This comment was minimized by the moderator on the site
Thank you. that was really helpful. Can someone please tell how to color the text instead of highlighting it?

Regards
This comment was minimized by the moderator on the site
Hi Shaik Faiaz hamad,

Excel does not allow coloring a part of a cell. I'm sorry I can't help you with this problem.
This comment was minimized by the moderator on the site
Thank you that is very useful. How can I Highlight a word instead of a font color?

Regards.
This comment was minimized by the moderator on the site
how could the script be altered to do the following?

increase the font by 1 size, and
highlight multiple words with one running of the script?

Thx!
This comment was minimized by the moderator on the site
Hi t.taln,

If you want to increae the font size by 1 and highlight multiple words at the same time, please add the following line after the line "xCell.Characters(Len(xStrTmp) + 1, xHStrLen).Font.ColorIndex = 3" in the VBA code.
Note: You need to know the current font size of the selected cell beforehand, and then enter a number one size larger than the original word. The number 12 in the line below is the font size I will assign to the matching words. And the original font size of the word is 11.
xCell.Characters(Len(xStrTmp) + 1, xHStrLen).Font.Size = 12
This comment was minimized by the moderator on the site
That's very nice, thx! I'm wondering if anyone knows how to make it work on Mac? Many thanks
Rated 5 out of 5
This comment was minimized by the moderator on the site
Ciao,
a me servirebbe evidenziare tutti i numeri (comprensivi di due decimali) da -10,00 a 0 in rosso e da 0 a +10,00 in verde. come posso fare per non aggiungere singolarmente ogni dato senza aggiungerli tutti manualmente?

Grazie mille
This comment was minimized by the moderator on the site
Hi Ciao,
Are your numbers located in different cells in a range? If so, you can create two conditional formatting rules (between -10 and 0, between 0 and 10) to highlight these numbers. If not, can you upload a screenshot of your data?
This comment was minimized by the moderator on the site
Buna,

Coloreaza cuvantul doar daca e la inceput. Daca e la mijloc in aceeasi casuta de excel sau la sfarsit nu-l coloreaza.
Ce anume as putea schimba in cod pentru a-l colora indiferent unde se afla in casuta excel?

Multumesc!
This comment was minimized by the moderator on the site
Hi Andreea,
If you only want to highlight the word if it is at the beginning of the selected cells. The following VBA code can do you a favor. Please give it a try.
Sub HighlightStrings()
'Updated by Extendoffice 20220805
    Dim xHStr As String, xStrTmp As String
    Dim xHStrLen As Long, xCount As Long, I As Long
    Dim xCell As Range
    Dim xArr
    On Error Resume Next
    xHStr = Application.InputBox("What is the string to highlight:", "KuTools For Excel", , , , , , 2)
    If TypeName(xHStr) <> "String" Then Exit Sub
    Application.ScreenUpdating = False
        xHStrLen = Len(xHStr)
        For Each xCell In Selection
            If xHStrLen <= Len(xCell.Value) Then
                If xHStr = Left(xCell.Value, xHStrLen) Then
                    xCell.Characters(1, xHStrLen).Font.ColorIndex = 3
                End If
            End If
        Next
    Application.ScreenUpdating = True
End Sub
This comment was minimized by the moderator on the site
Bonjour,
Est-il possible de supprimer la boite de dialogue et de mettre par défaut "apple" comme mot recherché ?
Merci
This comment was minimized by the moderator on the site
Hello PAUC,
The following code can do you a favor. Please give it a try.
Sub HighlightStrings()
'Updated by Extendoffice 20220721
    Dim xHStr As String, xStrTmp As String
    Dim xHStrLen As Long, xCount As Long, I As Long
    Dim xCell As Range
    Dim xArr
    On Error Resume Next
    xHStr = "apple"
    If TypeName(xHStr) <> "String" Then Exit Sub
    Application.ScreenUpdating = False
        xHStrLen = Len(xHStr)
        For Each xCell In Selection
            xArr = Split(xCell.Value, xHStr)
            xCount = UBound(xArr)
            If xCount > 0 Then
                xStrTmp = ""
                For I = 0 To xCount - 1
                    xStrTmp = xStrTmp & xArr(I)
                    xCell.Characters(Len(xStrTmp) + 1, xHStrLen).Font.ColorIndex = 3
                    xStrTmp = xStrTmp & xHStr
                Next
            End If
        Next
    Application.ScreenUpdating = True
End Sub
This comment was minimized by the moderator on the site
Thanks... this was very helpful! Is there a way to adjust the macro so that it only highlights whole words instead of partials. For instance, I'm trying to highlight the word "design" but it highlights the "design" in the word "designate". I want it to skip over that word if it's not the whole word. Thanks!
There are no comments posted here yet
Load More
Please leave your comments in English
Posting as Guest
×
Rate this post:
0   Characters
Suggested Locations