Note: The other languages of the website are Google-translated. Back to English
Log in  \/ 
x
or
x
Inscreva-se  \/ 
x

or

Como concatenar texto facilmente com base em critérios no Excel?

Supondo que eu tenha uma coluna de números de ID que contém algumas duplicatas e uma coluna de nomes, e agora, eu quero concatenar os nomes com base nos números de ID exclusivos conforme a imagem à esquerda mostrada, para combinar rapidamente o texto com base em critérios, como poderíamos fazer no Excel?

doc combinar texto com base nos critérios 1

Concatenar texto com base em critérios com função definida pelo usuário

Concatenar texto com base em critérios com Kutools para Excel


Para combinar texto com os números de ID exclusivos, você pode extrair os valores exclusivos primeiro e, em seguida, criar uma função definida pelo usuário para combinar os nomes com base no ID exclusivo.

1. Pegue os dados a seguir como exemplo, você precisa extrair os números de ID exclusivos primeiro, aplique esta fórmula de matriz: =IFERROR(INDEX($A$2:$A$15, MATCH(0,COUNTIF($D$1:D1, $A$2:$A$15), 0)),""), Insira esta fórmula em uma célula em branco, D2 por exemplo, e pressione Ctrl + Shift + Enter chaves juntas, veja a captura de tela:

doc combinar texto com base nos critérios 2

Ponta: Na fórmula acima, A2: A15 é o intervalo de dados da lista de onde você deseja extrair valores exclusivos, D1 é a primeira célula da coluna em que você deseja colocar o resultado da extração.

2. E, em seguida, arraste a alça de preenchimento para baixo para extrair todos os valores únicos até que os espaços em branco sejam exibidos, veja a captura de tela:

doc combinar texto com base nos critérios 3

3. Nesta etapa, você deve criar um Função definida pelo usuário para combinar os nomes com base nos números de identificação exclusivos, mantenha pressionado o ALT + F11 chaves, e abre o Microsoft Visual Basic para Aplicações janela.

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

Código VBA: concatene texto com base em critérios

Function ConcatenateIf(CriteriaRange As Range, Condition As Variant, ConcatenateRange As Range, Optional Separator As String = ",") As Variant
'Updateby Extendoffice
Dim xResult As String
On Error Resume Next
If CriteriaRange.Count <> ConcatenateRange.Count Then
    ConcatenateIf = CVErr(xlErrRef)
    Exit Function
End If
For i = 1 To CriteriaRange.Count
    If CriteriaRange.Cells(i).Value = Condition Then
        xResult = xResult & Separator & ConcatenateRange.Cells(i).Value
    End If
Next i
If xResult <> "" Then
    xResult = VBA.Mid(xResult, VBA.Len(Separator) + 1)
End If
ConcatenateIf = xResult
Exit Function
End Function

5. Em seguida, salve e feche este código, volte para sua planilha e insira esta fórmula na célula E2, = CONCATENATEIF ($ A $ 2: $ A $ 15, D2, $ B $ 2: $ B $ 15, ",") , veja a captura de tela:

doc combinar texto com base nos critérios 4

6. Em seguida, arraste a alça de preenchimento para baixo até as células às quais deseja aplicar esta fórmula, e todos os nomes correspondentes foram combinados com base nos números de ID, consulte a captura de tela:

doc combinar texto com base nos critérios 5

Dicas:

1. Na fórmula acima, A2: A15 são os dados originais que você deseja combinar com base, D2 é o valor exclusivo que você extraiu e B2: B15 é a coluna de nome que você deseja combinar.

2. Como você pode ver, combinei os valores que são separados por vírgula, você pode usar qualquer outro caractere alterando a vírgula “,” da fórmula conforme necessário.


Se você tem Kutools for Excel, Com o seu Combinar linhas avançadas utilitário, você pode concatenar de forma rápida e conveniente a base de texto em critérios.

Kutools for Excel : com mais de 300 suplementos úteis do Excel, grátis para testar sem limitação em 30 dias.

Depois de instalar Kutools for Excel, siga as seguintes etapas:

1. Selecione o intervalo de dados que você deseja combinar com base em uma coluna.

2. Clique Kutools > Unir e dividir > Combinar linhas avançadas, veja a captura de tela:

3. No Combinar linhas com base na coluna caixa de diálogo, clique na coluna ID e clique em Chave primária para tornar esta coluna a coluna-chave na qual seus dados combinados se baseiam, consulte a captura de tela:

doc combinar texto com base nos critérios 7

4. E, em seguida, clique em Nome coluna para a qual deseja combinar os valores e clique em Combinar opção e escolha um separador para os dados combinados, consulte a captura de tela:

doc combinar texto com base nos critérios 8

5. Depois de terminar essas configurações, clique em OK para sair da caixa de diálogo, e os dados na coluna B foram combinados com base na coluna-chave A. Veja a captura de tela:

doc combinar texto com base nos critérios 9

Com este recurso, o seguinte problema será resolvido o mais rápido possível:

Como combinar várias linhas em uma e somar duplicatas no Excel?

Baixe e teste grátis Kutools para Excel agora!


Kutools for Excel: com mais de 300 suplementos úteis do Excel, grátis para testar sem limitação em 30 dias. Baixe e teste grátis agora!

As melhores ferramentas de produtividade para escritório

O Kutools for Excel resolve a maioria dos seus problemas e aumenta sua produtividade em 80%

  • armadilha para peixes: Insira rapidamente fórmulas complexas, gráficos e qualquer coisa que você tenha usado antes; Criptografar células com senha; Criar lista de discussão e enviar emails ...
  • Super Formula Bar (edite facilmente várias linhas de texto e fórmula); Layout de leitura (ler e editar facilmente um grande número de células); Colar na faixa filtrada...
  • Mesclar células / linhas / colunas sem perder dados; Dividir o conteúdo das células; Combinar linhas / colunas duplicadas... Evite células duplicadas; Comparar intervalos...
  • Selecione Duplicado ou Único Linhas; Selecione linhas em branco (todas as células estão vazias); Super Find e Fuzzy Find em muitos livros; Seleção aleatória ...
  • Cópia exata Várias células sem alterar a referência da fórmula; Criação automática de referências para várias folhas; Inserir marcadores, Caixas de seleção e mais ...
  • Extrair Texto, Adicionar texto, remover por posição, Remover Espaço; Criar e imprimir subtotais de paginação; Converter entre conteúdo de células e comentários...
  • Super Filtro (salvar e aplicar esquemas de filtro a outras planilhas); Classificação Avançada por mês / semana / dia, frequência e mais; Filtro Especial por negrito, itálico ...
  • Combine pastas de trabalho e planilhas; Mesclar tabelas com base em colunas-chave; Divida os dados em várias folhas; Conversão em lote de xls, xlsx e PDF...
  • Mais de 300 recursos poderosos. Suporta Office / Excel 2007-2019 e 365. Suporta todos os idiomas. Fácil implantação em sua empresa ou organização. Teste gratuito de 30 dias com recursos completos. Garantia de devolução do dinheiro em 60 dias.
guia kte 201905

Guia do Office 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!
officetab bottom
Say something here...
symbols left.
You are guest
or post as a guest, but your post won't be published automatically.
Loading comment... The comment will be refreshed after 00:00.
  • To post as a guest, your comment is unpublished.
    Laurie S. · 2 months ago
    Great function!  Is there a way to maintain the format in the cell it's concatenating data from?  i.e. $45.07, $555.34, $0.00, $0.25, -$12.25   I've figured out how to stack them with wrap text and CHAR(10) in place of "," but having trouble keeping the format. I will be using this for a mail merge in Word.
    • To post as a guest, your comment is unpublished.
      skyyang · 2 months ago
      Hello, Laurie,
      If you want to keep the cell formatting when concatenating the data, you can apply the  Advanced Combine Rows feature of Kutools for Excel, in the dialog box, after finishing the settings, you just need to check Use formatted values option, and all the data formatting will be kept as you need.

      You can download Kutools for Excel and free trial  30-day.
  • To post as a guest, your comment is unpublished.
    Md. Zaker Hossain · 5 months ago
    Is there any way to add "and" instead of "," before the last data? (For example: D2355, D2273, D2397, D2600 and D2386)
    • To post as a guest, your comment is unpublished.
      skyyang · 5 months ago
      Hi, Hossain,
      May be there is not a direct method for solving your problem, you can add another formula to convert the last comma to the text "and".
      =SUBSTITUTE(E2,","," and ",LEN(E2)-LEN(SUBSTITUTE(E2,",","")))
      Please try, thank you!
      • To post as a guest, your comment is unpublished.
        Md. Zaker Hossain · 5 months ago
        It worked like a charm sir. Thank you so much.
  • To post as a guest, your comment is unpublished.
    AA · 9 months ago
    Great function, exactly what I needed! Works like a charm
  • To post as a guest, your comment is unpublished.
    AS · 2 years ago
    Hi,

    Very helpful VBA solution. Thank you kindly! My question is: Is there a way to change the code or function for multiple criteria? Although the code works for me, I need it to show values corresponding to a timestamp-interval (>= timestamp A, <= timestamp B)


    Thank you in advance. :)
  • To post as a guest, your comment is unpublished.
    Pete · 2 years ago
    Is there a way to assign this to a button? On large data ranges it takes a while, so ideally I only want it to start the concatenate process once I've finished doing everything else in the sheet. I tried adding a trigger myself but it stopped working completely
  • To post as a guest, your comment is unpublished.
    Merijn · 2 years ago
    BTW i used the VBA solution
  • To post as a guest, your comment is unpublished.
    Merijn · 2 years ago
    Extremely helpfull! After editing it for my sheet i have #VALUE! for some of the unique values.
    I did a countif to see if it could be that there are too many names to concatenate. The two unique values that have the #VALUE! error have 13635 and 19810 results. Is there a way to overcome this?
  • To post as a guest, your comment is unpublished.
    cadrose97 · 2 years ago
    How can I ignore blank cells? mine currently displays this:

    ";2503201111@msg.telus.com;;2503202222@msg.telus.com;2508193333@msg.telus.com;2503714444@msg.telus.com;;;;"

    I'd like for the 1st, 3rd and last 3 semi colons not to there/show. TIA
    • To post as a guest, your comment is unpublished.
      skyyang · 2 years ago
      Hello, Chantelle
      When concatenating the cell values ignoring the blank cells, please apply the below User Defined Function:

      Function ConcatenateIf(CriteriaRange As Range, Condition As Variant, ConcatenateRange As Range, Optional Separator As String = ",") As Variant
      Dim xResult As String
      On Error Resume Next
      If CriteriaRange.Count <> ConcatenateRange.Count Then
      ConcatenateIf = CVErr(xlErrRef)
      Exit Function
      End If
      For i = 1 To CriteriaRange.Count
      If CriteriaRange.Cells(i).Value = Condition Then
      If ConcatenateRange.Cells(i).Value <> "" Then
      xResult = xResult & Separator & ConcatenateRange.Cells(i).Value
      End If
      End If
      Next i
      If xResult <> "" Then
      xResult = VBA.Mid(xResult, VBA.Len(Separator) + 1)
      End If
      ConcatenateIf = xResult
      Exit Function
      End Function

      Please try it, hope it can help you!
  • To post as a guest, your comment is unpublished.
    victor · 2 years ago
    thank you very much! This was so simple and helped a lot!!
  • To post as a guest, your comment is unpublished.
    David · 3 years ago
    Is it possible to replace the comma splitter with a line break, i.e. char(10)? Many thanks.
    • To post as a guest, your comment is unpublished.
      skyyang · 3 years ago
      Hello, David,

      To combine the cells with line break, the following User Defined Function may help you.

      Function ConcatenateIf_LineBreak(CriteriaRange As Range, Condition As Variant, ConcatenateRange As Range, Optional Separator As String = ",") As Variant
      Dim xResult As String
      On Error Resume Next
      If CriteriaRange.Count <> ConcatenateRange.Count Then
      ConcatenateIf = CVErr(xlErrRef)
      Exit Function
      End If
      For I = 1 To CriteriaRange.Count
      If CriteriaRange.Cells(I).Value = Condition Then
      xResult = xResult & vbCrLf & ConcatenateRange.Cells(I).Value
      End If
      Next I
      If xResult <> "" Then
      xResult = VBA.Mid(xResult, VBA.Len(Separator) + 1)
      End If
      ConcatenateIf_LineBreak = xResult
      Exit Function
      End Function

      After pasting this code, then apply this formula: =ConcatenateIf_LineBreak(A2:A13,F2,B2:B13,",").

      After getting the results with this formula, you should click the Wrap Text to get the correct results you need.
  • To post as a guest, your comment is unpublished.
    Ahmed · 3 years ago
    So Easy, thank you :)
  • To post as a guest, your comment is unpublished.
    minhtien1900@gmail.com · 3 years ago
    Hi guys , I got an error #NAME? when I apply formulas CONCATENATEIF in excel file after set VBA code for this, could anyone help me to solve it , thanks som uch
  • To post as a guest, your comment is unpublished.
    krawlis · 4 years ago
    Is there a way to apply this CONCATENATEIF function in a separate sheet? It works when I put it in the same sheet as input data, but i need both tables in different sheets and it doesn't work.
    • To post as a guest, your comment is unpublished.
      al.boulley@gmail.com · 3 years ago
      Yes, what you want to do is add the function to a module. Go into the VBA editor, right-click on "VBAProject" in the Project Explorer, mouse over the "Insert" menu item, and in that submenu choose "Module". Any functions you put in there will be useable on any sheet in your workbook.
  • To post as a guest, your comment is unpublished.
    MIchele · 4 years ago
    Is there a way to do this on Mac????
    It's exactly what I need - please let me know (or if any mac software would do it that you know of). Thx
  • To post as a guest, your comment is unpublished.
    DJDave · 4 years ago
    I had a problem after pasting this code into Excel 2016 - it contains non-regular spaces (perhaps non-breaking spaces?) which throw up syntax errors which are not evident no matter how closely you look because they are invisible! It is the indentation spaces that are the problem. Paste the code into Word and turn on hidden characters to see them.
    • To post as a guest, your comment is unpublished.
      Yash · 4 years ago
      Wow!! Genius! Worked like a charm! There ARE come spaces that show as a different character. Thanks a lot Dave! Wonder how you came up with the idea! Also, wonder how it works for some other peeps..Anyway, thanks again!
  • To post as a guest, your comment is unpublished.
    Yash · 4 years ago
    Hi!

    concactenateif is Exactly what I was looking for. But unfortunately can´t get it to work Always get a compile error:syntax error. Any ideas?

    In the past, with some imported VBA modules, I have noticed that I had to replace the "," by ";" as in my PC, maybe owing to my regional settings, that's the only way it works. Avidly use the built in sumifs etc. But can´t understand where am going wrong on this one.

    One more possibility that comes to mind is the fact that in office 365, "concat" replaces "concactenate". Can you help out please?

    Thanks in advance,

    Yash
    • To post as a guest, your comment is unpublished.
      DJDave · 4 years ago
      The code uses some non-breaking spaces for indentation, these trip up Excel2016. Hard to spot an invisible error..
  • To post as a guest, your comment is unpublished.
    Ram Bahadur Ale · 4 years ago
    It does not work for the big data range. I found that its working datarange is up to A2:A362. We would be grateful if you share the solution to cover the wider data range like A2:A200000 .....
    Thank you
  • To post as a guest, your comment is unpublished.
    Ram Bahadur Ale · 4 years ago
    It does not work for the big data range. I found it's working range is only up to A2:A362. We would be grateful if you share the solution for the big data range like A2:A200000 ....

    Thank you
    • To post as a guest, your comment is unpublished.
      Chris · 4 years ago
      Works great just slow. I am doing it with 27k lines of text in excel just set it off go for a brew and leave it to run
  • To post as a guest, your comment is unpublished.
    nickado · 4 years ago
    Great!!! Thank you so much!
  • To post as a guest, your comment is unpublished.
    Matt · 4 years ago
    Awesome, thank you! I used the VBA solution and it worked great.
  • To post as a guest, your comment is unpublished.
    Samrat Govekar · 5 years ago
    Extremely helpful and nicely explained
  • To post as a guest, your comment is unpublished.
    Samrat Govekar · 5 years ago
    Explained in detailed and easy to understand, really helped when i was stuck at exact same situation.
  • To post as a guest, your comment is unpublished.
    latha · 5 years ago
    Taking more time for updating the same concatenateif() formula. i have 5000 rows. and its more than 2 hrs now its still updating :(

    Any resolution to make it work fast?
  • To post as a guest, your comment is unpublished.
    Renee · 5 years ago
    I am looking for a way to use a variation of this code to create a variant list based on master variant. Using your example data, I would need to combine columns A and B into unique identifiers and then concatenate those identifiers to each row based on the value in column A, excluding the value from from the combined for that row, and the rest in alpha sort order:

    Master id name id variant list
    CN20150012 Lucy CN20150012-Lucy CN20150012-Andy CN20150012-Monica CN20150012-Phiby
    US20150011 Tommas US20150011-Tommas US20150011-Rose
    CN20150012 Monica CN20150012-Monica CN20150012-Andy CN20150012-Lucy CN20150012-Phiby
    CN20150012 Phiby CN20150012-Phiby CN20150012-Andy CN20150012-Lucy CN20150012-Monica
    US20150011 Rose US20150011-Rose US20150011-Tommas
    UK20150014 Peter UK20150014-Peter UK20150014-Anith UK20150014-Kristi UK20150014-Libin
    JP20150010 Ramon JP20150010-Ramon JP20150010-Brenda JP20150010-James
    UK20150014 Libin UK20150014-Libin UK20150014-Anith UK20150014-Kristi UK20150014-Peter
    UK20150014 Anith UK20150014-Anith UK20150014-Kristi UK20150014-Libin UK20150014-Peter
    JP20150010 James JP20150010-James JP20150010-Brenda JP20150010-James JP20150010-Matus
    CN20150012 Andy CN20150012-Andy CN20150012-Lucy CN20150012-Monica CN20150012-Phiby
    UK20150014 Matus UK20150014-Matus JP20150010-Brenda JP20150010-James
    UK20150014 Kristi UK20150014-Kristi UK20150014-Anith UK20150014-Libin UK20150014-Peter
    JP20150010 Brenda JP20150010-Brenda JP20150010-James JP20150010-Ramon

    I have a sheet with over 1000 lines, each item comes with up to 4 variants. Trying to do this manually is impossible but I cannot find a solution that fits my needs.
  • To post as a guest, your comment is unpublished.
    Tim Blosser · 5 years ago
    This VBA code saved the day for me. Thank you!
  • To post as a guest, your comment is unpublished.
    Manoj · 5 years ago
    Will this tool be able to handle case sensitive combinations such as

    jABC 123
    abc 345
    ABc 678
    ABC 912
  • To post as a guest, your comment is unpublished.
    Enrique · 5 years ago
    Thanks for this code. It was EXACTLY what I needed. You saved me a lot of effort, thank you so much.
    • To post as a guest, your comment is unpublished.
      ConfusedNBusy · 4 years ago
      Thanks for posting this is exactly what I am looking for. I seem not to be saving the vba code correctly. I am getting an error message about ambiguous name found.

      Any suggestions or step by step on the VBA step of this project?

      Thanks
  • To post as a guest, your comment is unpublished.
    Kaladhar · 5 years ago
    This is an excellent solution (VBA code) and it addressed my requirements in minutes. I will refer your site to others and I will visit for everything that I need going forward.