Análise de Dados e Relatórios em Marketing
Estratégias e Tendências de Marketing Digital

A Fórmula Definitiva do Google Sheets Para Unir Tabelas

Ever wondered which formula you can use to join tables in Google Sheets? And automatically? The kind of magic formula that would be easy to reuse and does exactly what you need. If you want to know how, then read on.

Every user finds it extremely important to find an efficient Google Sheets formula that can work wonders for their data. However, it has been a challenge to get such effective formulas because chaining multiple functions can quickly create complex queries.

While many formulas are at our disposal, most require some creativity to make them ideal for your situations. So, when it comes to joining two or more tables, we have to depend on some other functions and reference knowledge to create a Google Sheets formula that can do the job effectively.

Se achou o processo de unir tabelas tedioso ou complicado, este artigo ajudará a entender tudo o que precisa de saber. Portanto, vamos mergulhar nesta fórmula do Google Sheets para unir as suas tabelas!

What Google Sheets formula do you need to join tables?

Como dissemos, juntar duas tabelas envolve combinar várias funções. A fórmula que vamos construir inclui duas poderosas funções do Google Sheets para unir as nossas tabelas: a FILTER e a VLOOKUP.

As you can see, the functions are not new, but when combined with a few other tricks, they can revolutionize how you process your most complex data. Before we dive into the formula, we need to solidify our understanding of these functions of the query before we can create it.

So, let’s roll up our sleeves and get down to business.

A função FILTER

Google Sheet formula FILTER is a powerful slice and dice function. The syntax for this function is:

Onde:

  • O intervalo é o intervalo de células que você deseja filtrar.
  • Condição1 is the row or column that corresponds to the dataset and returns an array with Boolean values: the TRUE or FALSE values based on your conditions.
  • Condição2: While this is an optional argument, it serves the same function as condition 1, helping you chain conditions. 

A função FILTER retorna a versão filtrada do seu intervalo. Ela retorna apenas as linhas ou colunas que atendem às condições especificadas que você fornece. 

Portanto, se esta função pode retornar uma linha ou uma coluna com base nas nossas condições, será uma das nossas funções úteis.

A função VLOOKUP

Quando você deseja se referir a dados de diferentes planilhas ou tabelas no Google Sheets, o função VLOOKUP é muito útil. Esta função de pesquisa vertical é poderosa e pode trabalhar com dados de folhas externas, tornando-a poderosa e perfeita para o nosso propósito.

You can use the Google Sheets formula VLOOKUP to source or lookup values that match another table, so here’s the syntax:

Onde:

  • A chave de pesquisa: O parâmetro search_key são os valores que queremos procurar. Você pode inserir os dados, como ‘Texas’, 3400 ou A12. Aqui, você pode combinar valores de várias colunas para obter uma coluna de pesquisa única.
  • O intervalo: The second parameter in the VLOOKUP Google Sheets formula is the range: the references to cells where you want to search your data. 
  • O índice: Outro parâmetro na função VLOOKUP é o índice. O índice é a posição da coluna que você deseja obter. O número da coluna sempre começa a partir da primeira célula do seu intervalo de pesquisa, começando de 1 e não 0.
  • O parâmetro is_sorted: The final parameter in a VLOOKUP function is the is_sorted. This parameter shows whether we should sort the first column in ascending order or not. So, its values can either be FALSE or TRUE. When set to FALSE, the search range will not be sorted and remains in the original order.

Ilustração do VLOOKUP

To illustrate how to join a table using the Google Sheets formula VLOOKUP, we will use the following tables for our example. Here, we have two tables that share a common key, the Nome.

AB
1NomeDepartamento
2EricVendas
3JaneTI
4JohnControle de Qualidade
Tabela A na FolhaA
AB
1NomeSalário
2Eric$45500
3Jane$31850
4John$21440
Tabela B na FolhaB

If we need a Google Sheets formula to join the two tables above, here’s how we will achieve the results in Sheet C below:

ABC
1NomeDepartamentoSalário
2EricVendas$45500
3JaneTI$31850
4JohnControle de Qualidade$21440
FolhaC

Tabela A lista os Nomes e Departamentos dos colaboradores. A segunda tabela lista os Nomes e os seus Salário. Se precisar de obter todos estes detalhes numa tabela, pode usar VLOOKUP. Irá corresponder cada nome na nova Tabela C (Onde tinha o Nomes apenas) com o nome correspondente em FolhaB

Como conseguimos?

Em B2 da Tabela C, we used this Google Sheets formula to get the Departamentos dos funcionários:

Onde:

A2 é a chave de pesquisa. FolhaA! é uma referência a FolhaA com tabela A. A2:B4 é nosso intervalo de pesquisa em Folha A. 2 é o índice da coluna que queremos selecionar em A2:B4.

Ativar C2 de FolhaC, use this Google Sheets formula to get the salary for the employees from FolhaB

Nota: Arraste a fórmula para outras células para obter seus valores.

Limitations of the VLOOKUP function and how to overcome

Vários inconvenientes vêm com o uso da função VLOOKUP sozinha. E se você quiser preencher toda a coluna ou linha sem fazê-lo manualmente? E se os valores que você está procurando não forem exclusivos? E se os valores que você está procurando não estiverem na primeira coluna do seu intervalo?

There are two straightforward Google Sheets formulas to deal with these limitations. Let’s check them out!

Usando concatenações

Concatenations are a way of chaining up values of two or more cells into a single value. When your columns have values that are not unique, this can be problematic for the VLOOKUP function. Therefore, we will use concatenation to create unique columns for this function to work optimally.

There are several ways to concatenate with Google Sheets formula, but we will only focus on the easiest: using the ampersand ‘&.’ For example, to concatenate cells A12 e A15, simplesmente use =A12&A15 como sua fórmula.

Because we want to do this virtually for our VLOOKUP Google Sheets formula, we will apply it to our search keys and range. So, let’s create another table with the following values:

ABC
1NomeEstadoSalário
2EricColorado$40,500
3JaneConnecticut$37,600
4EricDelaware$30,000
5JohnCalifórnia$52,000

If you try to duplicate or use VLOOKUP to populate another table with no unique values, the value of the first occurrence of the search key will be used throughout the search. Here’s an example of using the table above to reproduce the table. Check that the second Eric’s Estado e Salário não estão precisos.

To avoid IF errors, you can concatenate two cells or columns to make the key unique.

Para evitar tais erros, podemos concatenar duas células ou colunas para tornar a chave única, o que significa que teremos uma chance maior de obter dados precisos. Nós combinamos o Nome e Estado para diferenciar os dois Eric in the list. Here’s the complete Google Sheets formula: 

=VLOOKUP(H10&I10, {D10&E10, F10}, 2, FALSO)
You can use VLOOKUP to populate another table with no unique values, the value of the first occurrence of the search key will be used throughout the search.

Did you see we used the curly brackets to get that? What does it mean? To solve the other limitation of the Google Sheets formula VLOOKUP, we introduced the concept of arrays to allow us to create a virtual table and change the order of these tables without creating them manually.

Então, aqui vem a segunda solução para a limitação:

Usando arrays

O que são arrays no Google Sheets? If you have a background in coding, you should know what an array means. However, it may mean different when you use it in Google Sheets formula. Arrays are tables with columns or rows of values. 

Para diferenciar uma linha de valores de uma coluna de valores em um array, a vírgula é usada para representar colunas, e o ponto e vírgula representa as linhas. Se isso é confuso, aqui está um exemplo.

Se eu quiser representar nossos dados na nossa última tabela em um array, uma linha de Eric de Colorado será {Eric,Colorado,40500}. E as colunas de Nomes are represented as {Eric;Jane;Eric;John}.

Back to our usage above, after concatenating the Nomes e Estados, without arrays, you will need to create a Coluna Auxiliar to hold the concatenation. So, that is where arrays help us. With the arrays, we can now create a virtual column and use the VLOOKUP Google Sheets formula to use that table to get us the results we want.

Portanto, a tabela virtual do array {D10&E10, F10} significa que a tabela irá mesclar os valores de D10 e E10 em uma coluna, e adicione o valor de F10 para a próxima coluna. Assim, a tabela auxiliar completa deve parecer com esta:

You need to create a Helper Column to hold the concatenation.

Como lidar com erros nos resultados

Even when everything might seem right, sometimes errors might behave awkwardly in a Google Sheets formula. So, it is crucial to have a way to handle such issues. If you deal with a small dataset, you can find and fix the errors manually if it is well with you.

Um exemplo de erro é o #N/A erro que ocorre quando a chave de pesquisa na fórmula VLOOKUP não encontra dados em uma linha sem dados ou quando a função FILTER não encontra linhas correspondentes.

Felizmente, o Google Sheets fornece várias fórmulas para lidar com esses erros. Por exemplo, o IFNA encontrará as células com #N/A errors on your formula and replace them with a custom message. If you want to add zeros to such cells, here’s the Google Sheets formula:

Sintaxe:

For example, the Google Sheets formula:

While this example may seem ideal, nesting multiple error-handling formulas can make your functions complicated. The good news is that there is an alternative: the IFERROR function, which is a sort of universal catch-all for errors.

The syntax and usage are just like IFNA; that is, the Google Sheets formula:

Nossa fórmula em ação: Unindo duas tabelas no Google Sheets

Mas você se lembra da função FILTER que apresentamos anteriormente? Onde ela se encaixará nesta fórmula?

To answer that, let me introduce you to another limitation of the VLOOKUP function we haven’t discussed. The VLOOKUP function does not automatically populate other cells with values— you need to copy and paste or drag the formulas to use them in other cells.

Mas esse é outro trabalho que você não vai querer fazer. Então, como você pode superá-lo? Aqui está como você pode fazer isso:

Usando a função FILTER para preencher os resultados do VLOOKUP

Usando a função FILTER para filtrar os resultados do VLOOKUP sob a condição de que o intervalo não esteja vazio, você poderá mesclar suas tabelas no Google Sheets automaticamente.

In our example, our VLOOKUP function finds values from the range that we provided. The filter function will loop all the values for each cell in the VLOOKUP range until the condition becomes false; that is, when VLOOKUP returns nothing. The FILTER function then populates all the values received to their respective columns in our new table.

VLOOKUP Google Sheets formula finds values from the range that you provided.

As you have seen, we have joined three different tables using the VLOOKUP and FILTER functions. So, let’s now break down the formulas that we used:

A fórmula para conseguir Nome e Estado da Tabela 1:

Aqui, estamos a filtrar o intervalo de colunas de I10:I14 do intervalo I10 até K14 with VLOOKUP. Then we include an array index on the columns we want to pick from the range; that is, column index one and two, {1,2}: Nome e Estado.

A fórmula para conseguir País Favorito da Tabela 2:

Da nossa gama M10:N10, queremos selecionar a segunda coluna (não a ser ordenada), e nosso intervalo de colunas M10:M14 não deve estar vazio de acordo com nossa condição FILTER.

Finalmente, a fórmula para obter ID e Código de Área da Tabela 3:

Considerações finais sobre a consulta do Google Sheets para unir mais tabelas

Merging two tables can be daunting, but with the functional Google Sheets formula that we shared to join your tables, we believe it’s now easier. By combining two powerful functions that we already know and use, the process is even clearer.

To merge different tables with a Google Sheets formula, use the following syntax:

Se você ainda encontra dificuldades em usar essas fórmulas, considere usar Dataslayer para Google Sheets, que pode permitir que você facilmente mescle duas tabelas, importe dados de diferentes planilhas e trabalhe com mais de 40 fontes de dados diferentes para o seu relatório. Quer saber mais? Comece hoje gratuitamente!

COMO PODEMOS AJUDAR?

FORMULÁRIO DE CONTACTO

Estamos aqui para ajudar e responder a quaisquer perguntas que possa ter. Aguardamos o seu contacto.