Note: The other languages of the website are Google-translated. Back to English
Se connecter  \/ 
x
or
x
INSCRIPTION  \/ 
x

or

Comment copier la mise en forme source de la cellule de recherche lors de l'utilisation de Vlookup dans Excel?

Dans les articles précédents, nous avons parlé de conserver la couleur d'arrière-plan lorsque vlookup prend des valeurs dans Excel. Ici, dans cet article, nous allons présenter une méthode de copie de toute la mise en forme de cellule de la cellule résultante lors de Vlookup dans Excel. Veuillez faire comme suit.

Copier le formatage de la source lors de l'utilisation de Vlookup dans Excel avec une fonction définie par l'utilisateur


Copier le formatage de la source lors de l'utilisation de Vlookup dans Excel avec une fonction définie par l'utilisateur


Supposons que vous ayez un tableau comme ci-dessous. Vous devez maintenant vérifier si une valeur spécifiée (dans la colonne E) est dans la colonne A et renvoyer la valeur correspondante avec le formatage dans la colonne C. Veuillez procéder comme suit pour y parvenir.

1. Dans la feuille de calcul contient la valeur que vous souhaitez rechercher, cliquez avec le bouton droit sur l'onglet de la feuille et sélectionnez Voir le code dans le menu contextuel. Voir la capture d'écran:

2. Dans l'ouverture Microsoft Visual Basic pour applications , veuillez copier ci-dessous le code VBA dans la fenêtre Code.

Code VBA 1: Vlookup et valeur de retour avec mise en forme

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. Puis clique insérer > Module, et copiez le code VBA 2 ci-dessous dans la fenêtre Module.

Code VBA 2: Vlookup et valeur de retour avec mise en forme

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. Cliquez Outils > Références. Puis vérifiez le Exécution de scripts Microsoft boîte dans la Références - VBAProject boite de dialogue. Voir la capture d'écran:

5. appuie sur le autre + Q touches pour quitter Microsoft Visual Basic pour applications fenêtre.

6. Sélectionnez une cellule vide à côté de la valeur de recherche, puis entrez la formule =LookupKeepFormat(E2,$A$1:$C$8,3) into the Barre de formule, puis appuyez sur Entrer clé.

Notes: Dans la formule, E2 contient la valeur que vous rechercherez, 1 $ AU: 8 $ C $ est la plage de table et le nombre 3 signifie que la valeur correspondante que vous retournerez se situe dans la troisième colonne du tableau. Veuillez les changer selon vos besoins.

7. Continuez à sélectionner la première cellule de résultat, puis faites glisser la poignée de remplissage vers le bas pour obtenir tous les résultats avec leur mise en forme comme illustré ci-dessous.


Articles Liés:


Les meilleurs outils de productivité de bureau

Kutools for Excel résout la plupart de vos problèmes et augmente votre productivité de 80%

  • Réutilisation: Insérer rapidement formules complexes, graphiques et tout ce que vous avez utilisé auparavant; Crypter les cellules avec mot de passe; Créer une liste de diffusion et envoyer des e-mails ...
  • Barre Super Formula (modifiez facilement plusieurs lignes de texte et de formule); Disposition de lecture (lire et modifier facilement un grand nombre de cellules); Coller dans la plage filtrée...
  • Fusionner les cellules / lignes / colonnes sans perdre de données; Contenu des cellules divisées; Combiner des lignes / colonnes en double... Empêcher les cellules en double; Comparer les gammes...
  • Sélectionnez Dupliquer ou Unique Lignes; Sélectionnez les lignes vides (toutes les cellules sont vides); Super Find et Fuzzy Find dans de nombreux classeurs; Sélection aléatoire ...
  • Copie exacte Plusieurs cellules sans changer la référence de formule; Créer automatiquement des références à plusieurs feuilles; Insérer des puces, Cases à cocher et plus encore ...
  • Extrait du texte, Ajouter du texte, Supprimer par position, Supprimer l'espace; Créer et imprimer des sous-totaux de pagination; Conversion entre le contenu et les commentaires des cellules...
  • Super filtre (enregistrer et appliquer des schémas de filtrage à d'autres feuilles); Tri avancé par mois / semaine / jour, fréquence et plus; Filtre spécial par gras, italique ...
  • Combiner des classeurs et des feuilles de travail; Fusionner les tableaux en fonction des colonnes clés; Diviser les données en plusieurs feuilles; Conversion par lots xls, xlsx et PDF...
  • Plus de 300 fonctionnalités puissantes. Prend en charge Office / Excel 2007-2019 et 365. Prend en charge toutes les langues. Déploiement facile dans votre entreprise ou organisation. Essai gratuit de 30 jours. Garantie de remboursement de 60 jours.
onglet kte 201905

Office Tab apporte une interface à onglets à Office et simplifie considérablement votre travail

  • Activer l'édition et la lecture par onglets dans Word, Excel, PowerPoint, Publisher, Access, Visio et Project.
  • Ouvrez et créez plusieurs documents dans de nouveaux onglets de la même fenêtre, plutôt que dans de nouvelles fenêtres.
  • Augmente votre productivité de 50% et réduit des centaines de clics de souris chaque jour!
bas de cabine
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 · 3 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 · 3 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.