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

or

Como copiar a formatação de origem da célula de pesquisa ao usar o Vlookup no Excel?

Nos artigos anteriores, falamos sobre como manter a cor de fundo quando vlookup valores no Excel. Aqui neste artigo, vamos apresentar um método de copiar toda a formatação de célula da célula resultante ao fazer Vlookup no Excel. Faça o seguinte.

Copie a formatação de origem ao usar o Vlookup no Excel com uma função definida pelo usuário


Copie a formatação de origem ao usar o Vlookup no Excel com uma função definida pelo usuário


Supondo que você tenha uma tabela como a imagem mostrada abaixo. Agora você precisa verificar se um valor especificado (na coluna E) está na coluna A e retornar o valor correspondente com formatação na coluna C. Faça o seguinte para obtê-lo.

1. Na planilha contém o valor que você deseja ver, clique com o botão direito na guia da planilha e selecione Ver código no menu de contexto. Veja a imagem:

2. Na abertura Microsoft Visual Basic para Aplicações janela, copie o código VBA abaixo na janela Código.

Código VBA 1: Vlookup e valor de retorno com formatação

Sub Worksheet_Change(ByVal Target As Range)
'Update by Extendoffice 20211203
    Dim I As Long
    Dim xKeys As Long
    Dim xDicStr As String
    On Error Resume Next
    Application.ScreenUpdating = False
    Application.CutCopyMode = False
    xKeys = UBound(xDic.Keys)
    If xKeys >= 0 Then
        For I = 0 To UBound(xDic.Keys)
            xDicStr = xDic.Items(I)
            If xDicStr <> "" Then
                Set xRg = Application.Range(xDicStr)
                xRg.Copy
                Range(xDic.Keys(I)).PasteSpecial xlPasteFormats
            Else
                Range(xDic.Keys(I)).Interior.Color = xlNone
            End If
        Next
        Set xDic = Nothing
    End If
    Application.ScreenUpdating = True
    Application.CutCopyMode = True
End Sub

3. Então clique inserção > Móduloe copie o código 2 do VBA abaixo na janela Módulo.

Código VBA 2: Vlookup e valor de retorno com formatação

Public xDic As New Dictionary
'Update by Extendoffice 20211203
Function LookupKeepFormat(ByRef FndValue, ByRef LookupRng As Range, ByRef xCol As Long)
    Dim xFindCell As Range
    On Error Resume Next
    Application.ScreenUpdating = False
    Set xFindCell = LookupRng.Find(FndValue, , xlValues, xlWhole)
    If xFindCell Is Nothing Then
        LookupKeepFormat = " "
        xDic.Add Application.Caller.Address, " "
    Else
        LookupKeepFormat = xFindCell.Offset(0, xCol - 1).Value
        xDic.Add Application.Caller.Address, xFindCell.Offset(0, xCol - 1).Address(External:=True)
    End If
    Application.ScreenUpdating = True
End Function

4. Clique Ferramentas > Referências. Em seguida, verifique o Microsoft Script Runtime caixa no Referências - VBAProject caixa de diálogo. Veja a imagem:

5. aperte o outro + Q chaves para sair do Microsoft Visual Basic para Aplicações janela.

6. Selecione uma célula em branco adjacente ao valor de pesquisa e insira a fórmula =LookupKeepFormat(E2,$A$1:$C$8,3) no Barra de Fórmula, e depois pressione o botão Entrar chave.

Importante: Na fórmula, E2 contém o valor que você procurará, $ A $ 1: $ C $ 8 é o intervalo da mesa e o número 3 significa que o valor correspondente que você retornará está localizado na terceira coluna da tabela. Altere-os conforme necessário.

7. Continue selecionando a primeira célula de resultado e, em seguida, arraste a alça de preenchimento para baixo para obter todos os resultados junto com sua formatação, conforme mostrado na imagem abaixo.


Artigos relacionados:


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.
    kirtiraj · 12 days ago
    This code only works when data is in same sheet.
    • To post as a guest, your comment is unpublished.
      crystal · 4 days ago
      Hi kirtiraj,
      To lookup values across worksheets and keep the formatting, you need to place the VBA code 1 in the code window of the result worksheet, and place the VBA code 2 in the Module code window.

  • To post as a guest, your comment is unpublished.
    John · 3 months ago
    I get a compile error: "Expected: end of statement", with the word "New" highlighted in: "Public xDic As New Dictionary".

    I'm not a developer, just trying to solve a problem in a long set of sheets.  So thank you for the help.
  • To post as a guest, your comment is unpublished.
    M B · 6 months ago
    Hey
    The code does not work in Microsoft Excel 2019 (16.0.13929.20360) 64-bit
    Can provide details if asked...
    • To post as a guest, your comment is unpublished.
      ed · 4 months ago
      Please provide details
  • To post as a guest, your comment is unpublished.
    ABCD · 6 months ago
    How to make this work if the value we are trying to look up sits in a different worksheet?
    • To post as a guest, your comment is unpublished.
      crystal · 4 days ago
      Hi,
      To lookup values across worksheets and keep the formatting, you need to place the VBA code 1 in the code window of the result worksheet, and place the VBA code 2 in the Module code window.
  • To post as a guest, your comment is unpublished.
    Jeff · 6 months ago
    So, I got this to work. However, how I'm using it is I have the lookupkeepformat formula already entered in multiple rows. I then enter a letter (A-J) in column A and this letter tells the lookup formula which data I want. After it pulls the data, the cursor ends up in the cell where it finished entering the lookup data. How can I have the cursor return to column A?
  • To post as a guest, your comment is unpublished.
    Jeff · 7 months ago
    I'm getting an error

  • To post as a guest, your comment is unpublished.
    Rah2153 · 11 months ago
    I am adding these modules to my PERSONAL.XLSB file. I have Outlook 2016. And when I use this user-defined function, my excel doesn't crash or give an error. But it does not pull in the format of the source cell. It only pulls in the value. Since this function is located in the PERSONAL.XLSB file, my formula looks like this;
    =PERSONAL.xlsb!LookupKeepFormat(E2,$A$1:$C$8,3)
    I had copied the code into 2 modules as directed, but this just doesn't work. Any ideas why?

  • To post as a guest, your comment is unpublished.
    Gustavo · 11 months ago
    I get the same Ambiguous name error - has anyone managed to solve it ?
  • To post as a guest, your comment is unpublished.
    John · 2 years ago
    I get the same Ambiguous name error - has anyone managed to solve it ?
  • To post as a guest, your comment is unpublished.
    phappe · 2 years ago
    Here is the file and pic
  • To post as a guest, your comment is unpublished.
    phappe · 2 years ago
    HI, I am new to using VBA and tried using this code in my spreadsheet, but the text formatting on the Rec2 tab doesn't come over to Rec tab when lookup is used. Any help would be greatly appreciated. Thanks Pat
  • To post as a guest, your comment is unpublished.
    Gareth · 2 years ago
    hi i got the error "compile Error: Ambigious name detected: xDic
  • To post as a guest, your comment is unpublished.
    Jack · 2 years ago
    hi i got the error "compile Error: Ambigious name detected: xDic
  • To post as a guest, your comment is unpublished.
    A. · 2 years ago
    Hello, Thanks for the code. I do not get any error message but the formula only works as a normal vlookup would. Could you please assist? Thanks for your time.
    • To post as a guest, your comment is unpublished.
      Joel · 2 years ago
      Hello

      I have exactly the same issue, did you figure out how to solve it?

      Thanks!
  • To post as a guest, your comment is unpublished.
    ShdwWlf1065 · 2 years ago
    Hello, I've been using the above code in Excel 2010 with no problems to date. However, I was recently upgraded to Office 2016 and now the code crashes Excel every time I try to fill down more than one row. Unfortunately, it is not giving me an error other than "Microsoft Excel has stopped working". I was wondering if you have come across this issue previously, and if there is something I need to do to make it work in 2016. Thanks!
    • To post as a guest, your comment is unpublished.
      crystal · 2 years ago
      Hi Leigh,
      The code works well in my Excel 2016. We are trying to upgrad the code to solve the problem. Thank you for your comment.
  • To post as a guest, your comment is unpublished.
    Laura · 3 years ago
    Hello. I created a blank spreadsheet and duplicated your example in Excel 2013, but keep getting a Compile error: Syntax error and Dim I As Long is highlighted. Is there something I'm missing? I would love to get this working. Thank you.
    • To post as a guest, your comment is unpublished.
      crystal · 2 years ago
      Hi Laura,
      Don't forget to enable the Microsoft Script Runtime option as mentioned in step 4.
  • To post as a guest, your comment is unpublished.
    jenittu · 3 years ago
    I tried this one and the the one that pulls just the color background and am getting the same error. Compile error: Ambiguous name detected. I click OK and it highlights xDic. Any suggestions? I'm not super familiar with all of this so please help/explain :) thanks in advance
    • To post as a guest, your comment is unpublished.
      crystal · 2 years ago
      Hi Jeni,
      Don't forget to enable the Microsoft Script Runtime option as mentioned in step 4.
  • To post as a guest, your comment is unpublished.
    LadyBug679 · 3 years ago
    Also, if I add your formula as part of an "If" statement (see below), it formats the cell however it wants LOL (or at least it seems so. One cell, the text went shadowed and bold with a top border on the cell; another cell, the text centered)


    =IF($F19 = "", "",LookupKeepFormat(F19,'Item #s'!$A$1:$M$1226,2))
  • To post as a guest, your comment is unpublished.
    LadyBug679 · 3 years ago
    Hi,

    I get no errors and it does the lookup, but because my lookup value is on another worksheet (a more likely scenario), it doesn't pull the formatting. Is there a tweak to the code that I can make for that? (Be very specific as to where the change needs to go as I'm a coding novice) Thank you! I'm excited to add this feature to one of my spreadsheets!!
    • To post as a guest, your comment is unpublished.
      Chirag · 3 years ago
      Hi, any luck on this question, how can we get the formatting to be looked up across sheets?
      • To post as a guest, your comment is unpublished.
        Justin · 3 years ago
        Also seeking the tweak.
  • To post as a guest, your comment is unpublished.
    nivian.govender@gmail.com · 3 years ago
    Hi There


    I have tried to use the code however I am getting the error in the attached pic. Any assisting will be greatly appreciated.
    • To post as a guest, your comment is unpublished.
      crystal · 3 years ago
      Hi,
      Sorry for the mistake, the code has been updated in the article. Thank you for your comment.
  • To post as a guest, your comment is unpublished.
    Julia · 3 years ago
    Greatly appreciate the follow-up Hugo!
    Unfortunately like Vi, I am too much of a novice to work out where to insert your suggested code fixes...

    Thanks again, have a great day :)
  • To post as a guest, your comment is unpublished.
    Phan · 3 years ago
    Hey Hugo,


    I have the same problem as Julia. It doesn't work on other sheets. Could you help write code for the whole function and sub worksheet? I am not sure where to replace/insert xDic.Add Application.Caller.Address, xFindCell.Offset(0, xCol - 1).Address & "|" & LookupRng.Parent.Nam and Sheets(Split(xDic.Items(I), "|")(1)).Range(Split(xDic.Items(I), "|")(0)).Copy


    thanks in return
  • To post as a guest, your comment is unpublished.
    Hugo · 3 years ago
    Julia, correct this lines:
    in Function LookupKeepFormat:
    xDic.Add Application.Caller.Address, xFindCell.Offset(0, xCol - 1).Address & "|" & LookupRng.Parent.Name

    in Sub Worksheet_Change:
    Sheets(Split(xDic.Items(I), "|")(1)).Range(Split(xDic.Items(I), "|")(0)).Copy
  • To post as a guest, your comment is unpublished.
    Julia · 3 years ago
    This is great, thank you! The only problem is, I find it works fine if I'm looking up in the same sheet, but can't get it to work when I'm trying to do a lookup in a separate sheet to the source data. Will keep trying
  • To post as a guest, your comment is unpublished.
    ltballard2@gmail.com · 3 years ago
    I got the same error.

    You will have to change the &quot; &quot for actual "', without ';' as indicated below
    LookupKeepFormat = &quot; &quot;
    xDic.Add Application.Caller.Address, &quot; &quot;

    LookupKeepFormat = ""
    xDic.Add Application.Caller.Address ""
    • To post as a guest, your comment is unpublished.
      crystal · 3 years ago
      Hi,
      Sorry for the mistake, the code has been updated in the article. Thank you for sharing.
  • To post as a guest, your comment is unpublished.
    ltballard · 3 years ago
    I also got the compiler error.
    It gets corrected if you change the following variable with actual "". No ';' in the middle.
    LookupKeepFormat = &quot; &quot;
    xDic.Add Application.Caller.Address, &quot; &quot
    • To post as a guest, your comment is unpublished.
      crystal · 3 years ago
      Hi,
      Sorry for the mistake, the code has been updated in the article.
      The mistake &quot; &quot; should be two quotation marks " ". Thank you for your comment.
  • To post as a guest, your comment is unpublished.
    Sayed · 3 years ago
    it give me Compile Error ,Syntax error

    please help
    • To post as a guest, your comment is unpublished.
      crystal · 3 years ago
      Good Day,
      The code has been updated in the artcle. Thank you for your comment.