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

Как изменить цвет ячейки при нажатии или выборе ячейки в Excel?

В этой статье будут показаны некоторые методы изменения цвета ячейки при нажатии на ячейку и изменение выделенного цвета при выборе диапазона ячеек в Excel.

Изменить цвет ячейки при нажатии на ячейку с кодом VBA
Измените выделенный цвет, когда ячейки выбраны с помощью кода VBA
Выделите всю строку и столбец активной ячейки с помощью Kutools for Excel


Изменить цвет ячейки при нажатии на ячейку с кодом VBA

Здесь вы можете изменить цвет фона ячейки, дважды щелкнув по ней или щелкнув правой кнопкой мыши с помощью следующего кода VBA.

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

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

VBA: изменить цвет ячейки при нажатии на нее

Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
    Target.Interior.Color = vbRed
End Sub
Private Sub Worksheet_BeforeRightClick(ByVal Target As Range, Cancel As Boolean)
    Target.Interior.Color = vbGreen
End Sub

3. Нажмите другой + Q клавиши одновременно, чтобы закрыть Microsoft Visual Basic для приложений окно.

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


Один щелчок, чтобы выделить строку и столбец выбранной ячейки в Excel:

Kutools for Excel's Макет для чтения Утилита помогает быстро выделить строку и столбец выбранной ячейки в Excel, как показано в демонстрации ниже.
Скачайте и попробуйте прямо сейчас! (30-дневный бесплатный пробный период)


Измените выделенный цвет, когда ячейки выбраны с помощью кода VBA

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

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

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

Код VBA: изменить выделенный цвет выбранного диапазона

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    With Target
        .Worksheet.Cells.FormatConditions.Delete
        .FormatConditions.Add xlExpression, , "TRUE"
        .FormatConditions(1).Interior.Color = vbYellow
    End With
End Sub

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

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


Выделите всю строку и столбец активной ячейки с помощью Kutools for Excel

Если вы имеете дело с большим листом, необходимо выделить всю строку и столбец активной ячейки, чтобы облегчить чтение. Здесь Макет для чтения полезности Kutools for Excel могу помочь тебе.

Перед применением Kutools for Excel, Пожалуйста, сначала скачайте и установите.

1. Нажмите Кутулс > Макет для чтения. Смотрите скриншот:

Когда макет чтения включен, вы можете видеть, что строка и столбец активной ячейки сразу выделяются.

Внимание: Вы можете изменить настройки макета чтения в зависимости от ваших потребностей, как показано на скриншоте ниже.

  Если вы хотите получить бесплатную (30-дневную) пробную версию этой утилиты, пожалуйста, нажмите, чтобы загрузить это, а затем перейдите к применению операции в соответствии с указанными выше шагами.


Выделите всю строку и столбец активной ячейки с помощью Kutools for Excel

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

🤖 Kutools AI Помощник: Революционный анализ данных на основе: Интеллектуальное исполнение   |  Генерировать код  |  Создание пользовательских формул  |  Анализ данных и создание диаграмм  |  Вызов функций Kutools...
Популярные опции: Найдите, выделите или определите дубликаты   |  Удалить пустые строки   |  Объедините столбцы или ячейки без потери данных   |   Раунд без формулы ...
Супер поиск: Множественный критерий VLookup    VLookup с несколькими значениями  |   VLookup по нескольким листам   |   Нечеткий поиск ....
Расширенный раскрывающийся список: Быстрое создание раскрывающегося списка   |  Зависимый раскрывающийся список   |  Выпадающий список с множественным выбором ....
Менеджер столбцов: Добавить определенное количество столбцов  |  Переместить столбцы  |  Переключить статус видимости скрытых столбцов  |  Сравнить диапазоны и столбцы ...
Рекомендуемые функции: Сетка Фокус   |  Просмотр дизайна   |   Большой Формулный Бар    Менеджер книг и листов   |  Библиотека ресурсов (Авто текст)   |  Выбор даты   |  Комбинировать листы   |  Шифровать/дешифровать ячейки    Отправлять электронные письма по списку   |  Суперфильтр   |   Специальный фильтр (фильтровать жирным шрифтом/курсивом/зачеркиванием...) ...
15 лучших наборов инструментов12 Текст Инструменты (Добавить текст, Удалить символы, ...)   |   50+ График Тип (Диаграмма Ганта, ...)   |   40+ Практических Формулы (Рассчитать возраст по дню рождения, ...)   |   19 Вносимые Инструменты (Вставить QR-код, Вставить изображение из пути, ...)   |   12 Конверсия Инструменты (Числа в слова, Конверсия валюты, ...)   |   7 Слияние и разделение Инструменты (Расширенные ряды комбинирования, Разделить клетки, ...)   |   ... и более

Улучшите свои навыки работы с Excel с помощью Kutools for Excel и почувствуйте эффективность, как никогда раньше. Kutools for Excel предлагает более 300 расширенных функций для повышения производительности и экономии времени.  Нажмите здесь, чтобы получить функцию, которая вам нужна больше всего...

Описание


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

  • Включение редактирования и чтения с вкладками в Word, Excel, PowerPoint, Издатель, доступ, Visio и проект.
  • Открывайте и создавайте несколько документов на новых вкладках одного окна, а не в новых окнах.
  • Повышает вашу продуктивность на 50% и сокращает количество щелчков мышью на сотни каждый день!
Comments (28)
No ratings yet. Be the first to rate!
This comment was minimized by the moderator on the site
Hello, i built a dashboard with 37 worksheets, everyone with a table. All of them are lock panels because are to large and i need to know the number and name of the student who am i entering data for. Despite that, i have to keep my finger on the left side of the screen to identify the names and numbers to which the entered data refer.  So, i need to identify the first two cells of the row, in the columns "I" and "J".
The code that i took from the internet and couldn't change for the two cells of columns "I" and "J" was:

Dim lTarget As Range

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

If Target.Row >= 16 Then

If Not lTarget Is Nothing Then

lTarget.EntireRow.Interior.ColorIndex = 0
End If

Target.EntireRow.Interior.Color = 9359529

Set lTarget = Target
End If
End Sub

All tables begin in diferent rows. This example start in 16 row but i put the code in all the pages and adapt to the needs of the specific row number. 
I've already tried to change the code from EntireRow to Range ("I16:J43") but the cells were in the range became all painted with the code color.
Already try a diferent way through the "conditional formatting" with the formula =E($I16<>"";LIN()=CÉL("lin")) in the range $I16:$J43, and in the developer "worksheet", with "Application.Calculate" and it works. I change in the 37 worksheets but i was copying and data from the previous file to this new one and I noticed that the options to paste "values", etc, disappear from my dashboard. The code must be executing something that, like clicking on the cell, no longer lets it paste. A single option was to paste with CTRL+V.
If someone can help me with the code, i'll delete the VBA "Application.Calculate" to to get back to the available collage options.
Thak you for your help.

Luís Lopes
This comment was minimized by the moderator on the site
Hello, the code used to work for a while, but now it doesn't anymore. What can there be wrong?
This comment was minimized by the moderator on the site
Hi Rens Borburgh,There are two codes provided in the post, which one did you use? Did you get any error prompt?
This comment was minimized by the moderator on the site
I have tried them both at the same time. After copying it to a usb stick it didn't work anymore.
This comment was minimized by the moderator on the site
Hi Rens Borburgh,I don't quite understand what you mean. The codes should be used in the sheet code window and not in the Module window. Or can you provide a screenshot of your code window?
This comment was minimized by the moderator on the site
Hi, I am trying to use the double click option to change a cell to green but i also want that cell to go back to no fill or white if i double click it whilst it is green. Is this possible? 
This comment was minimized by the moderator on the site
alguien que me ayude solo quiero que al hacerle click a una celda se ponga de un color y que se mantenga ese color y si le vuelvo hacer click regrese el color original que tenia
This comment was minimized by the moderator on the site
How to highlight the cell(with data) to automatically highlight the other cells (data which is related another data in a previous cell) with click of the cell.Can i do it. Is there a way to do it.
This comment was minimized by the moderator on the site
The code works as long as I do not protect the worksheet. Once I protect the worksheet, because I have conditional formatting on locked cells, the code will not work. How can I change this so that it works on locked worksheet where the user can select unlocked cells?
This comment was minimized by the moderator on the site
Hi,
is it possible to have a code for "change cell color when clicking on it" in the way that it will not change already formated cells with another color, please?
After applying your code all my formating (colours) is away. Thank you. Veronika
This comment was minimized by the moderator on the site
Thank you. Great Job
This comment was minimized by the moderator on the site
hi
the is working grate but i want that the color should only be when the cell is selected and when i select something else, the first cell i selcted should not be colored
can you help me pls with this thanks
This comment was minimized by the moderator on the site
I had that exact same question! I hope someone will answer you! The reason I am looking for this is I have a spreadsheet I use daily and put in lots of information into single cells. It gets hard to see the values (visually, it runs into info in other cells), and would be a great feature if I could change the color of the cell being edited - only while it is being edited. The simplest solution I can think of is that the cell value would be set back to what it was prior to being clicked on - but I don't know how to do that.
This comment was minimized by the moderator on the site
Hi, I am trying to figure out how to change the color of a cell, based on a selection from a dropdown list. For example, HIGH=red, MEDIUM=yellow, LOW=green.

Any tips you can provide are greatly appreciated. Thank You
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