Перейти к основному содержанию

Как вставить раскрывающийся список с цветовой кодировкой в ​​таблицу Word?

Предположим, у меня есть таблица в моем документе Word, и теперь я хочу вставить раскрывающийся список с цветовой кодировкой в ​​столбец таблицы. Это означает, что когда я выбираю один вариант из раскрывающегося списка, цвет ячейки становится красным, а когда я выбираю другой вариант в раскрывающемся списке, цвет ячейки становится зеленым, как показано на следующем снимке экрана. Как бы вы могли решить эту задачу в документе Word?

раскрывающийся список с цветовой кодировкой документа

Вставить раскрывающийся список с цветовой кодировкой в ​​документ Word с кодом VBA


Вставить раскрывающийся список с цветовой кодировкой в ​​документ Word с кодом VBA

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

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

раскрывающийся список с цветовой кодировкой документа 1

2. Выпадающий список вставляется в конкретную ячейку, а затем щелкните Застройщик > Объекты, см. снимок экрана:

раскрывающийся список с цветовой кодировкой документа 2

3. В Свойства управления содержимым диалоговом окне выполните следующие действия:

(1.) Введите название заголовка в Название текстовое окно;

(2.) Щелкните Добавить кнопка перейти к Добавить выбор диалог;

(3.) В Добавить выбор диалоговом окне введите элемент раскрывающегося списка в Display Name текстовое окно.

раскрывающийся список с цветовой кодировкой документа 3

4. Повторите шаг 3, чтобы вставить другие элементы раскрывающегося списка по мере необходимости.

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

раскрывающийся список с цветовой кодировкой документа 4

6. Затем вы должны применить код VBA, удерживая ALT + F11 , чтобы открыть Microsoft Visual Basic для приложений окно.

7. В Microsoft Visual Basic для приложений окно, дважды щелкните Этот документ из Проект-Проект панель, чтобы открыть режим, а затем скопируйте и вставьте следующий код в пустой модуль.

Код VBA: вставить раскрывающийся список с цветовым кодированием в таблицу документа Word:

Private Sub Document_ContentControlOnExit(ByVal ContentControl As ContentControl, Cancel As Boolean)
With ContentControl.Range
    If ContentControl.Title = "Status" Then
        Select Case .Text
            Case "Complete"
                .Cells(1).Shading.BackgroundPatternColor = wdColorRed
            Case "In Progress"
                .Cells(1).Shading.BackgroundPatternColor = wdColorGreen
            Case "Not Start"
                .Cells(1).Shading.BackgroundPatternColor = wdColorBlue
            Case Else
                .Cells(1).Shading.BackgroundPatternColor = wdColorAutomatic
        End Select
    End If
End With
End Sub

раскрывающийся список с цветовой кодировкой документа 5

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

8. Затем сохраните и закройте окно кода, теперь, когда вы выбираете один элемент из раскрывающегося списка, его относительный цвет будет заполнен ячейкой, см. Снимок экрана:

раскрывающийся список с цветовой кодировкой документа


 

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

Kutools for Word - Повысьте свой опыт работы со словом с помощью Over 100 Замечательные особенности!

🤖 Kutools AI Помощник: Преобразуйте свое письмо с помощью искусственного интеллекта. Создать контент  /  Переписать текст  /  Обобщение документов  /  Запросить информацию на основе документа, все в Word

📘 Владение документами: Разделить страницы  /  Объединить документы  /  Экспортировать выбранное в различные форматы (PDF/TXT/DOC/HTML...)  /  Пакетное преобразование в PDF  /  Экспортировать страницы как изображения  /  Печать нескольких файлов одновременно...

Редактирование содержания: Пакетный поиск и замена через несколько файлов  /  Изменить размер всех изображений  /  Транспонировать строки и столбцы таблицы  /  Преобразовать таблицу в текст...

🧹 Легкая очистка: Убрать Дополнительные места  /  Разрывы разделов  /  Все заголовки  /  Текстовые поля  /  Гиперссылки  / Чтобы получить дополнительные инструменты для удаления, посетите наш Удалить группу...

Креативные вставки: Вставлять Разделители тысяч  /  Флажки  /  радио кнопки  /  QR код  /  Штрих-код  /  Таблица диагональных линий  /  Заголовок уравнения  /  Заголовок изображения  /  Заголовок таблицы  /  Несколько изображений  / Узнайте больше в Вставить группу...

???? Точный выбор: Точно определить конкретные страницы  /  Эта таблица  /  формы  /  заголовки абзацев  / Улучшите навигацию с помощью БОЛЕЕ Выберите функции...

Звездные улучшения: Быстро перемещайтесь в любое место  /  автоматическая вставка повторяющегося текста  /  плавно переключаться между окнами документов  /  11 инструментов преобразования...

👉 Хотите попробовать эти функции? Kutools for Word предлагает 60-дневная бесплатная пробная версия, без ограничений! 🚀
 

 

Comments (54)
Rated 5 out of 5 · 1 ratings
This comment was minimized by the moderator on the site
hello . i tried but it not go.
This comment was minimized by the moderator on the site
bonjour, je ne parviens pas à enregistrer
This comment was minimized by the moderator on the site
I have a word document that i would like some help with, in short, i have a large inspection table, items either comply, don't, further information etc. I currently use a simple drop-down option which has 5-6 options, ill like a selection option that when different options are selected, that changes the cells/row to a red or green etc, and then also (If possible) updates a Summary Table? is this possible, I'll pay someone for a general templet i can the work on....

Thank you in advance....
This comment was minimized by the moderator on the site
Hello, peter,
Did you mean to select an item from the drop down list, and a specific background color is filled for that row?
Please view the attachment to check if it is your need. If this is not your need, please give your problem more clearly.
Thank you!
This comment was minimized by the moderator on the site
Almost, by changing the drop-down tab the whole row changes color, perfect, thank you, however the magic is then coping the row (Yet only rows that don't comply or need further info etc... ) and placing it in a summary table at the top of the page in another table etc... getting them all to keep adding would be great in a summary table.

I can then alter the summary table as things change, and it updated the main parent table .... I'm not sure this is possible.

I'm happy to have a Teams Meeting to get this working, it would be apricated as it is doing my head in...

This comment was minimized by the moderator on the site
Hi, this is great, got me over a major problem with my fillable form. However, when I go to protect my fillable form, it brings up the debugger box? any idea how i can overcome this?
This comment was minimized by the moderator on the site
Thank you, i have managed to change the background colour. Is there a way i can change the text to white?
This comment was minimized by the moderator on the site
Hello, Emily,
To change the text color to white, please apply the following code:
Private Sub Document_ContentControlOnExit(ByVal ContentControl As ContentControl, Cancel As Boolean)
With ContentControl.Range
    If ContentControl.Title = "Status" Then
        Select Case .Text
            Case "Complete"
                .Cells(1).Shading.BackgroundPatternColor = wdColorRed
                .Cells(1).Range.Font.Color = wdColorWhite
            Case "In Progress"
                .Cells(1).Shading.BackgroundPatternColor = wdColorGreen
                .Cells(1).Range.Font.Color = wdColorWhite
            Case "Not Start"
                .Cells(1).Shading.BackgroundPatternColor = wdColorBlue
                .Cells(1).Range.Font.Color = wdColorWhite
            Case Else
                .Cells(1).Shading.BackgroundPatternColor = wdColorAutomatic
        End Select
    End If
End With
End Sub

Please have a try, hope it can help you!
This comment was minimized by the moderator on the site
What code do you add so it goes back to the normal colours (both background and text) when you select "Choose an item" from dropdown list after previously selecting a case
This comment was minimized by the moderator on the site
Hello, Usama,
In this case, the code in this article can help you. When uou select an item and then do back to choosing "Choose an item", the backdround color will not be filled.
Please try again. Thank you!
This comment was minimized by the moderator on the site
Well done! Is it possible to activate different cells (independent of row and column) with an item of the ContentControl... e.g. if we put the alphabet of English letters in a table with 6 rows and 5 columns and want to activate the vowels or the consonants?
This comment was minimized by the moderator on the site
Well done! Is it possible to activate different cells (independent of row and column) with an item of the ContentControl... e.g. if we put the alphabet of English letters in a table with 6 rows and 5 columns and want to activate the vowels or the consonants?
This comment was minimized by the moderator on the site
Hi I want a drop down list of colours but i do not want any text in the cells, i just want my users to be able to choose a colour as I am creating a RAG rated form.

is this possible?

thanks.
This comment was minimized by the moderator on the site
Probably way too late, but in case anyone else is wondering, you can probably do something like this by just adapting the code a bit.

adjust the range.font.color line with the same wd color code as the code above. Its not perfect but if the font is the same color as the highlight, you wont be able to visually see the difference
This comment was minimized by the moderator on the site
I have pasted the code and can see my drop down options (the text) but when I choose them, the background colors don't apply. Do you have any way to help me figure out what I may be doing wrong? Please and thank you! This is exactly what I'm hoping to do in my document, if I can make it work. Thanks!
This comment was minimized by the moderator on the site
Hello, Susan
You should check if the corresponding text in the VBA code has been mofified to your own contents.

Note: In the above code, Status is the title name when you creating the drop down list, and Complete, In Progress, Not Start are the items of the drop down list, you can change them to your own. And you can also change the color to your need.

If there is still problem after changing the text, you can upload the attachment word file and we will help you check it.
Thank you!
This comment was minimized by the moderator on the site
I am having the same issue.
I have changed the titles names in the code and followed the rest of the instructions.
Can you please tell me what I may have done wrong?
There are no comments posted here yet
Load More
Please leave your comments in English
Posting as Guest
×
Rate this post:
0   Characters
Suggested Locations