Combinar nome e sobrenome numa única célula pode ser uma necessidade comum na criação de relatórios ou formulários de entrada de dados. Em vez de manter campos separados para nome e sobrenome, é frequentemente preferível exibir o nome completo do usuário em uma única coluna. Essa abordagem simplifica a pesquisa e a organização dos dados, além de torná-los mais intuitivos para análises futuras.
Felizmente, Excel oferece várias opções para unir eficientemente dados de duas ou mais células. Desde o uso do operador Ampersand (&) até as funções integradas CONCATENATE, CONCAT e TEXTJOIN, passando por técnicas mais avançadas como Power Query e Power Pivot, este guia explora em detalhes 9 métodos para combinar nomes e sobrenomes no Excel.
Combinar nomes com o operador Ampersand
O operador Ampersand (&) é uma ferramenta simples e eficaz para concatenar texto de diferentes células. Suponha que você tenha os nomes na coluna B e os sobrenomes na coluna C, você pode usar a seguinte fórmula para uni-los na coluna D:
= B3 & " " & C3
Esta fórmula adicionará um espaço entre o nome e o sobrenome. Se desejar, você pode substituir o espaço por outro caractere ou delimitador, como uma vírgula.
A função CONCATENATE do Excel permite unir facilmente o conteúdo de várias células em uma única célula. Essa função é particularmente útil para criar nomes completos. A sintaxe da função é a seguinte:
CONCATENATE(testo1, [testo2], ...)
Onde testo1, testo2, etc. representam os valores a serem concatenados. Por exemplo:
= CONCATENATE(B3, " ", C3)
Esta fórmula combinará o conteúdo das células B3 e C3, inserindo um espaço entre elas.
A função CONCAT permite concatenar texto de vários intervalos de células em uma única célula. Essa função é útil quando você tem dados distribuídos em várias células adjacentes e deseja combiná-los em uma única célula para uso em fórmulas ou para fins de visualização. A sintaxe da função é a seguinte:
CONCAT(testo1, [testo2], ...)
Onde testo1, testo2, etc. representam os intervalos de células a serem concatenados. Por exemplo:
= CONCAT(B3:D3)
Esta fórmula combinará o conteúdo das células no intervalo B3:D3 em uma única célula.
A função TEXTJOIN permite unir texto de várias células em uma única célula, com um delimitador personalizado entre os valores concatenados. Este método permite unir nomes e sobrenomes sem a necessidade de adicionar uma coluna intermediária contendo um espaço. A sintaxe da função é a seguinte:
TEXTJOIN(delimitatore, ignora_vuoti, testo1, [testo2], ...)
Onde:
delimitatoreé o caractere ou conjunto de caracteres que você deseja usar para separar os valores concatenados;ignora_vuotipermite ignorar células vazias durante a concatenação;testo1,testo2, etc. represent the cell ranges to be concatenated.
For example:
= TEXTJOIN(" ", TRUE, B3:C3)
This formula will combine the values in cells B3 and C3, inserting a space between them. The parameter TRUE indicates to ignore any empty cells.
Excel’s Flash Fill function allows you to quickly populate a column of data based on a few examples provided by the user. This function can be particularly useful for quickly creating a column of full names from separate first and last name columns.
To use Flash Fill, simply type a few examples of full names in the cells adjacent to the corresponding first and last names. Excel will automatically recognize the pattern and complete the rest of the column.
If Flash Fill does not activate automatically after entering the first examples, you can activate it manually by following these steps:
- Select the first empty cell where you want Flash Fill to be applied.
- Go to the “Data” tab and click on the “Flash Fill” icon.
- Alternatively, you can use the keyboard shortcut Ctrl + E.
Power Query is an Excel tool that allows you to extract and transform data from various sources, such as databases, web pages, and text files. It can also be used to combine names in Excel. Here are the steps to follow:
- Select the Excel table containing the first and last name data.
- Go to the “Data” tab and choose the “From Table/Range” option.
- In the Power Query Editor, select the first and last name columns.
- Right-click on the column headers and choose “Merge Columns”.
- In the “Merge Columns” dialog box, select space as the separator and give a name to the new column, for example, “FullName”.
- Click “OK” to apply the transformation.
- Finally, click “Close & Load” to insert the combined data into the worksheet.
Power Pivot is an Excel data analysis tool that allows you to manipulate large datasets and create pivot tables and charts. It can also be used to combine names.
After loading the dataset into the Power Pivot data model, you can add a new calculated column using the DAX language. The simple Ampersand (&) operator can be used to concatenate first and last names. For example, if the names are in the “First” column and the last names are in the “Last” column, the formula to create the new “FullName” column would be:
= [First] & " " & [Last]
This formula will combine the values of the “First” and “Last” columns with a space in between. Once the new calculated column is created, you can use it in pivot tables.
VBA (Visual Basic for Applications) is Excel’s built-in programming language that allows you to automate tasks and processes. You can write a VBA macro to combine first and last names in Excel.
Here are the steps to create and use the macro:
- Open the VBA editor (Alt + F11).
- Insert a new module and add the following code:
Sub CombineNames()
Dim rng As Range
Dim arrNames() As Variant
Dim colCount As Long
Dim rowCount As Long
Set rng = Selection
rowCount = rng.Rows.Count
colCount = rng.Columns.Count
ReDim arrNames(colCount)
If colCount < 2 Then
MsgBox ("Seleziona almeno due colonne!")
Exit Sub
End If
For i = 1 To rowCount
For j = 1 To colCount
arrNames(j) = rng.Cells(i, j).Value
Next j
rng.Cells(i, colCount).Offset(0, 1).Value = Trim(Join(arrNames, " "))
Next i
End Sub
- Save the macro and add it to the Quick Access Toolbar to be able to run it easily.
This macro will check that at least two columns have been selected, then it will combine the values of each row into a new adjacent column, using a space as a delimiter.
Office Scripts is an Excel online feature that allows you to record and save macros as scripts to be executed in Excel. Here’s how to use Office Scripts to combine names:
- Open Excel online and go to the “Automate” tab.
- Clique em “Novo script” para abrir o editor de Office Scripts.
- Adicione o seguinte código:
function main(workbook: ExcelScript.Workbook) {
let rng = workbook.getSelectedRange();
let rows = rng.getRowCount();
let cols = rng.getColumnCount();
if (cols < 2) {
return;
}
for (let i = 0; i < rows; i++) {
let varName = rng.getRow(i).getValues()[0].join(" ");
rng.getCell(i, cols).setValue(varName);
}
}
- Salve o script e dê um nome a ele, por exemplo, “CombineNames”.
- Selecione as colunas de nome e sobrenome na planilha.
- Na guia “Automatizar”, selecione o script “CombineNames” e clique em “Executar”.
Este script verificará se pelo menos duas colunas foram selecionadas e, em seguida, combinará os valores de cada linha em uma nova coluna adjacente, usando um espaço como delimitador.
Conclusões
Combinar nome e sobrenome em uma única célula é uma tarefa comum na criação de relatórios ou formulários de entrada de dados no Excel. Felizmente, o Excel oferece várias opções para realizar essa tarefa de forma eficiente e flexível. Desde fórmulas simples que usam o operador Ampersand (&) ou as funções integradas CONCATENATE, CONCAT e TEXTJOIN, até técnicas mais avançadas como Power Query e Power Pivot, passando pela automação com VBA e Office Scripts, este guia apresentou 9 métodos para combinar nomes e sobrenomes no Excel.
Independentemente das necessidades do seu projeto, você certamente terá uma ferramenta adequada para unir de forma eficiente os dados de nome e sobrenome em uma única célula. Escolha o método que melhor se adapta às suas necessidades e aproveite os benefícios de ter nomes completos organizados de forma clara e intuitiva.
Pubblicato in Excel
Seja o primeiro a comentar