Ir para o conteúdo principal

Como remover caracteres ou palavras duplicadas em uma string de uma célula?

Supondo que haja palavras ou caracteres duplicados em cada célula e você queira remover as duplicatas e deixar apenas caracteres ou palavras exclusivos. Como você resolveria esse problema no Excel?

Remova os caracteres duplicados da string de texto com a função definida pelo usuário

Remova as palavras duplicadas separadas por pontuação com a função definida pelo usuário


seta azul bolha direita Remova os caracteres duplicados da string de texto com a função definida pelo usuário

Se você tem uma lista de string de texto, agora, você precisa remover os caracteres duplicados como mostrado a seguir. Aqui, posso falar sobre um código VBA para lidar com isso.

doc-remover-caracteres duplicados-1

1. Segure o ALT + F11 chaves para abrir o Janela Microsoft Visual Basic for Applications.

2. Clique inserção > Móduloe cole o seguinte código no Janela Módulo.

Código VBA: remove caracteres duplicados de string de texto em uma célula

Function RemoveDupes1(pWorkRng As Range) As String
'Updateby Extendoffice
Dim xValue As String
Dim xChar As String
Dim xOutValue As String
Set xDic = CreateObject("Scripting.Dictionary")
xValue = pWorkRng.Value
For i = 1 To VBA.Len(xValue)
    xChar = VBA.Mid(xValue, i, 1)
    If xDic.Exists(xChar) Then
    Else
        xDic(xChar) = ""
        xOutValue = xOutValue & xChar
    End If
Next
RemoveDupes1 = xOutValue
End Function

3. Em seguida, salve e feche este código, volte para a planilha e insira esta fórmula = removedupes1 (A2) (A2 é a célula de dados da qual você deseja remover duplicatas) em uma célula em branco ao lado de seus dados, consulte a captura de tela:

doc-remover-caracteres duplicados-1

4. Em seguida, arraste a alça de preenchimento até as células do intervalo às quais deseja aplicar esta fórmula, todos os caracteres duplicados foram removidos de cada célula imediatamente.

doc-remover-caracteres duplicados-1


seta azul bolha direita Remova as palavras duplicadas separadas por pontuação com a função definida pelo usuário

Se houver algumas palavras separadas por certos sinais de pontuação em uma célula, você também pode remover as palavras duplicadas conforme desejar. Execute as seguintes etapas:

1. Mantenha pressionada a ALT + F11 chaves para abrir o Janela Microsoft Visual Basic for Applications.

2. Clique inserção > Móduloe cole o seguinte código no Janela Módulo.

Código VBA: remova palavras duplicadas separadas pela pontuação de uma célula

Function RemoveDupes2(txt As String, Optional delim As String = " ") As String
    Dim x
    'Updateby Extendoffice
    With CreateObject("Scripting.Dictionary")
        .CompareMode = vbTextCompare
        For Each x In Split(txt, delim)
            If Trim(x) <> "" And Not .exists(Trim(x)) Then .Add Trim(x), Nothing
        Next
        If .Count > 0 Then RemoveDupes2 = Join(.keys, delim)
    End With
End Function

3. Em seguida, salve e feche este código, retorne à planilha e insira esta fórmula = RemoveDupes2 (A2, ",") em uma célula em branco ao lado de seus dados, veja a captura de tela:

doc-remover-caracteres duplicados-1

4. Em seguida, copie a fórmula para as células necessárias e todas as palavras duplicadas serão removidas de todas as células. Veja a imagem:

doc-remover-caracteres duplicados-1

Note: Na fórmula acima, A2 indica a célula que você deseja usar, e a vírgula (,) representa a marca de pontuação que separa as palavras em uma célula, você pode alterá-la para qualquer outra pontuação de sua necessidade.

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 (67)
No ratings yet. Be the first to rate!
This comment was minimized by the moderator on the site
How to remove duplicate words in excel template


Flooring|Tiles Flooring|Flooring|Vitrified Tiles|Tiles|Flooring|Tiles
This comment was minimized by the moderator on the site
Not sure if this thread is still alive. I am trying to use this for something as simple as what is shown in the chart above and I keep on receiving #NAME? error. Cell A2 has XXX, YYY, XXX, AAA I can't quite understand what I am doing wrong. I have the code in my personal workbook. Would that be the issue?
This comment was minimized by the moderator on the site
Thank you for the beautiful and useful coding. Can we do the same using Power Query?
This comment was minimized by the moderator on the site
Hi, is there a way to get the result of "RemoveDupes2" alphabetically sorted?
This comment was minimized by the moderator on the site
Hey! can anyone help me,
I have a data in excel example:



CARITAS, CSCED, FREE, NRC
BOSADP, DHCBI
BOSADP, Mercy Corps, NRC
ADRA, NRC
BOSADP, CAID
AAH, FAO (NEYIF), CRS (NEYIF)
SWNI, Mercy Corps,
CARE, PLAN, NRC
Mercy Corps, NRC
BOSADP, DHCBI, GREENCODE, NRC, AAH BOSADP


What I really want

CARITAS
BOSADP
DHCBI
NRC
ADRA
CAID
AAH
FAO
NEYIF
CRS
SWNI
CARE
PLAN
Mercy Corps
GREENCODE
FREE


the repeated words separated by comma deleted and and those that not repeated but separated by comma move to the next columns
This comment was minimized by the moderator on the site
Hey! can anyone help me,
I have a data in excel example:



CARITAS, CSCED, FREE, NRC
BOSADP, DHCBI
BOSADP, Mercy Corps, NRC
ADRA, NRC
BOSADP, CAID
AAH, FAO (NEYIF), CRS (NEYIF)
SWNI, Mercy Corps,
CARE, PLAN, NRC
Mercy Corps, NRC
BOSADP, DHCBI, GREENCODE, NRC, AAH BOSADP


What I really want

CARITAS
BOSADP
DHCBI
NRC
ADRA
CAID
AAH
FAO
NEYIF
CRS
SWNI
CARE
PLAN
Mercy Corps
GREENCODE
FREE


the repeated words separated by comma deleted and and those that not repeated but separated by comma move to the next columns
This comment was minimized by the moderator on the site
i tried applying method2 to numbers but it does not work. eg. 1104, 1104, 203, 203, 409, 409 >>>1104, 203, 409 How do you get method 2 to work with numbers?
This comment was minimized by the moderator on the site
Hello, deezy,
The second method works well for numbers, please see the below screenshot.
Please try it again, thank you!
This comment was minimized by the moderator on the site
Thanks so much for sharing knowledge, I used the "Remove Duplicate Words Separated By Punctuation With User Defined Function" and it worked great. May you knowledge grow and grow.
This comment was minimized by the moderator on the site
how about to remove duplicate character with an exception

for example from MMMPXLL, i want to remove M but keep the L

so the result will be MPXLL
This comment was minimized by the moderator on the site
Edit :

some problem solved with removedupes2, but i have to do it one by one

for example i cant remove duplicate letter y,a,l at once. I have to do it one by one.

also, for case there is data like this yyypl, it become pl, the "y" is totally removed
This comment was minimized by the moderator on the site
i have a string of text like so

1 Ser 1 Ser 1 Ser 1 Ser 1 Ser 1 Ser 1 Ser 1 Ser 1 Ser 2 Ser 2 Ser 2 Ser 2 Ser 2 Ser 2 Ser 2 Ser 2 Ser 3 Ser 3 Ser 3 Ser 3 Ser 3 Ser 3 Ser 3 Ser 3 Ser X3 X5

when applying remove dupes 2 i get

1 Ser 2 3 X3 X5


by the looks of it, all duplicates except the first instance are kept, is there any way to tweek this so all duplicate instances except the last occurance are kept ?

so my desired outcome would be

1 2 3 Ser X3 X5

thank you in advanced!
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