Note: The other languages of the website are Google-translated. Back to English
Войти  \/ 
x
or
x
Регистрация  \/ 
x

or

Как скопировать исходное форматирование ячейки поиска при использовании Vlookup в Excel?

В предыдущих статьях мы говорили о сохранении цвета фона при значениях vlookup в Excel. В этой статье мы собираемся представить метод копирования всего форматирования ячеек полученной ячейки при выполнении Vlookup в Excel. Пожалуйста, сделайте следующее.

Копирование исходного форматирования при использовании Vlookup в Excel с пользовательской функцией


Копирование исходного форматирования при использовании Vlookup в Excel с пользовательской функцией


Предположим, у вас есть таблица, как показано на скриншоте ниже. Теперь вам нужно проверить, находится ли указанное значение (в столбце E) в столбце A, и вернуть соответствующее значение с форматированием в столбце C. Для этого сделайте следующее.

1. На листе, содержащем значение, которое вы хотите просмотреть, щелкните правой кнопкой мыши вкладку листа и выберите Просмотреть код из контекстного меню. Смотрите скриншот:

2. В дебюте Microsoft Visual Basic для приложений окно, скопируйте ниже код VBA в окно кода.

Код VBA 1: Vlookup и возвращаемое значение с форматированием

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. Затем нажмите Вставить > Модульи скопируйте приведенный ниже код VBA 2 в окно модуля.

Код VBA 2: Vlookup и возвращаемое значение с форматированием

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. Нажмите Сервис > дело. Затем проверьте Среда выполнения сценария Microsoft коробка в Ссылки - VBAProject диалоговое окно. Смотрите скриншот:

5. нажмите другой + Q ключи для выхода из Microsoft Visual Basic для приложений окно.

6. Выберите пустую ячейку рядом с поисковым значением и введите формулу. =LookupKeepFormat(E2,$A$1:$C$8,3) в Панель формул, а затем нажмите Enter ключ.

Внимание: В формуле E2 содержит значение, которое вы будете искать, 1 австралийский доллар: 8 канадских долларов это диапазон таблицы, а число 3 означает, что соответствующее значение, которое вы вернете, находится в третьем столбце таблицы. Пожалуйста, измените их по своему усмотрению.

7. Продолжайте выбирать первую ячейку результата, а затем перетащите маркер заполнения вниз, чтобы получить все результаты вместе с их форматированием, как показано на скриншоте ниже.


Статьи по теме:


Лучшие инструменты для работы в офисе

Kutools for Excel решает большинство ваших проблем и увеличивает вашу производительность на 80%

  • Снова использовать: Быстро вставить сложные формулы, диаграммы и все, что вы использовали раньше; Зашифровать ячейки с паролем; Создать список рассылки и отправлять электронные письма ...
  • Бар Супер Формулы (легко редактировать несколько строк текста и формул); Макет для чтения (легко читать и редактировать большое количество ячеек); Вставить в отфильтрованный диапазон...
  • Объединить ячейки / строки / столбцы без потери данных; Разделить содержимое ячеек; Объединить повторяющиеся строки / столбцы... Предотвращение дублирования ячеек; Сравнить диапазоны...
  • Выберите Дубликат или Уникальный Ряды; Выбрать пустые строки (все ячейки пустые); Супер находка и нечеткая находка во многих рабочих тетрадях; Случайный выбор ...
  • Точная копия Несколько ячеек без изменения ссылки на формулу; Автоматическое создание ссылок на несколько листов; Вставить пули, Флажки и многое другое ...
  • Извлечь текст, Добавить текст, Удалить по позиции, Удалить пробел; Создание и печать промежуточных итогов по страницам; Преобразование содержимого ячеек в комментарии...
  • Суперфильтр (сохранять и применять схемы фильтров к другим листам); Расширенная сортировка по месяцам / неделям / дням, периодичности и др .; Специальный фильтр жирным, курсивом ...
  • Комбинируйте книги и рабочие листы; Объединить таблицы на основе ключевых столбцов; Разделить данные на несколько листов; Пакетное преобразование xls, xlsx и PDF...
  • Более 300 мощных функций. Поддерживает Office / Excel 2007-2019 и 365. Поддерживает все языки. Простое развертывание на вашем предприятии или в организации. Полнофункциональная 30-дневная бесплатная пробная версия. 60-дневная гарантия возврата денег.
вкладка kte 201905

Вкладка Office: интерфейс с вкладками в Office и упрощение работы

  • Включение редактирования и чтения с вкладками в Word, Excel, PowerPoint, Издатель, доступ, Visio и проект.
  • Открывайте и создавайте несколько документов на новых вкладках одного окна, а не в новых окнах.
  • Повышает вашу продуктивность на 50% и сокращает количество щелчков мышью на сотни каждый день!
офисный дно
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.
    slb · 27 days ago
    Is there a way to use this on the same sheet with two different lookups. Ie. Lookup Column M in array A:B, return column B with formatting. Then Lookup in Column N in array C:D and return column D with formatting?

    Ive got the first set working perfectly, and the second set wont work at all. No error, just most of the rows are blank
  • To post as a guest, your comment is unpublished.
    kirtiraj · 1 months ago
    This code only works when data is in same sheet.
    • To post as a guest, your comment is unpublished.
      crystal · 1 months 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 · 4 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 · 7 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 · 5 months ago
      Please provide details
  • To post as a guest, your comment is unpublished.
    ABCD · 8 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 · 1 months 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 · 8 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 · 8 months ago
    I'm getting an error

  • To post as a guest, your comment is unpublished.
    Rah2153 · 1 years 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 · 1 years 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.