Перейти до основного матеріалу

Як виділити активну комірку або виділення в Excel?

Якщо у вас великий робочий аркуш, можливо, вам важко з першого погляду дізнатись активну комірку або активний вибір. Але якщо активна комірка / секція має видатний колір, з’ясувати це не складе труднощів. У цій статті я розповім про те, як автоматично виділити активну комірку або вибраний діапазон комірок у Excel.

Виділіть активну комірку або виділення кодом VBA


стрілка синя права міхур Виділіть активну комірку або виділення кодом VBA

Наступний код VBA може допомогти вам динамічно виділити активну комірку або виділення, будь-ласка, зробіть наступне:

1. Утримуйте клавішу ALT + F11 ключі, щоб відкрити Вікно Microsoft Visual Basic для програм.

2. Тоді виберіть ThisWorkbook зліва Провідник проектів, двічі клацніть на ньому, щоб відкрити Модулі, а потім скопіюйте та вставте наступний код VBA у порожній модуль:

Код VBA: виділити активну комірку або виділення

Sub Workbook_SheetSelectionChange(ByVal Sh As Object, ByVal Target As Excel.Range)
'Update 20140923
Static xLastRng As Range
On Error Resume Next
Target.Interior.ColorIndex = 6
xLastRng.Interior.ColorIndex = xlColorIndexNone
Set xLastRng = Target
End Sub

doc-highlight-active-cell-1

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

Примітки:

1. Якщо ви не можете знайти файл Панель Провідника проекту у вікні ви можете клацнути вид > Провідник проектів в Вікно Microsoft Visual Basic для програм щоб його відкрити.

2. У наведеному вище коді ви можете змінити .ColorIndex = 6 колір до іншого кольору, який вам подобається.

3. Цей код VBA можна застосувати до всіх аркушів книги.

4. Якщо на вашому аркуші є кольорові клітинки, колір буде втрачено, коли ви клацаєте клітинку та переходите до іншої комірки.


Пов'язана стаття:

Як автоматично виділити рядок і стовпець активної комірки в Excel?

Найкращі інструменти продуктивності офісу

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

Покращуйте свої навички Excel за допомогою Kutools для Excel і відчуйте ефективність, як ніколи раніше. Kutools для Excel пропонує понад 300 додаткових функцій для підвищення продуктивності та економії часу.  Натисніть тут, щоб отримати функцію, яка вам найбільше потрібна...

Опис


Вкладка Office Передає інтерфейс із вкладками в Office і значно полегшує вашу роботу

  • Увімкніть редагування та читання на вкладках у Word, Excel, PowerPoint, Publisher, Access, Visio та Project.
  • Відкривайте та створюйте кілька документів на нових вкладках того самого вікна, а не в нових вікнах.
  • Збільшує вашу продуктивність на 50% та зменшує сотні клацань миші для вас щодня!
Comments (16)
No ratings yet. Be the first to rate!
This comment was minimized by the moderator on the site
I had the same problem, read the whole page and comments. While thinking to apply it or not, I was just randomly clicking on number and letters to select the whole column and rows. Then suddenly highlight of selected cell feature came back :)
This comment was minimized by the moderator on the site
Hello, if someone can help me... I pick up this code in internet (apologies to the owner). It does almost what i need but this code select the entirerow. What i need is a change that alow to select just the first two cells of the row of the activecells. When i click in the cell, i need that the cell of the column "$I16" and "$J16" (16 is the first line of my table) of that row became interior color (=9359529). The code is this: 
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

Can you help me? I had try to change this code but the only thing i can as the select the interior color of the cell target and not the column "$I" and "$J" in that specific row.Thank you for your help.
Luis Lopes
This comment was minimized by the moderator on the site
I know that you proposed a solution but the solution comes with another problem as you described below: "The only problem with having this code active is that you can no longer change the active cell color as it changes back to what it was before you clicked it. I suggest that if you need to change the highlight colors on the sheet, do so with macros disabled or change the sub name for a second so it doesn't trigger when you are clicking on cells". This is not an acceptable alternative for me. I need to be able to change the colors in the cells when the macro is active. Do you have a solution for this this problem. If you come up with a solution for this problem please republish your corrected macro the new macro in full (rather than proposing patches to your original macro because I am technically challenged as far as macro are concerned).
This comment was minimized by the moderator on the site
I tried your macro by copying and pasting it into my Excel file. I did change one thing in the macro though. I changed the color index from 6 to 24 (to a color different than the colors I am currently using in my macro). It worked very nicely and I liked it a lot but then started causing a problem for me. I have a lot of cells filled with with colors in my Excel. The macro started removing the color fill from every cell touched. I don't know how to stop the macro's this odd behavior. I did not have any choice but to remove the macro from my file. I still like to use this macro if someone can help me to fix it.
This comment was minimized by the moderator on the site
That was super helpful, thank you.
This comment was minimized by the moderator on the site
Anyway you can do the left adjacent cell to highlight instead of active cell? Or a range of cells around the activecell?
This comment was minimized by the moderator on the site
Thank you, but use this with caution. It has the undesirable counter effect of not letting undo. Is there any solution for that?
This comment was minimized by the moderator on the site
But i am unable to do undo option and lose the previously assigned cell color also.
Please provide solution
This comment was minimized by the moderator on the site
Perfect solution as I always tend to loose the track of the highlighted cell during "Find and Select" operation. Thanks a lot.
This comment was minimized by the moderator on the site
Great!! But what if I don't want to lose the previously assigned cell color? That would be greater to know.
This comment was minimized by the moderator on the site
Use a conditional format on the cells you want to protect.
This comment was minimized by the moderator on the site
Instead of "ColorIndex" which has a limited set of 255 values (meaning any custom colors are lost), use "Color" instead. You'll need to store the old value in a new static long variable and also generate the highlight color you want with the RGB function. The only problem with having this code active is that you can no longer change the active cell color as it changes back to what it was before you clicked it. I suggest that if you need to change the highlight colors on the sheet, do so with macros disabled or change the sub name for a second so it doesn't trigger when you are clicking on cells, then just rename it back to normal to "re-activate" it. Here is my code:

Sub Workbook_SheetSelectionChange(ByVal Sh As Object, ByVal Target As Excel.Range)

Static xLastRng As Range
Static xLastRngColor As Long

On Error Resume Next

xLastRng.Interior.Color = xLastRngColor
xLastRngColor = Target.Interior.Color
Target.Interior.Color = RGB(255, 255, 0) 'compose whatever highlight color you want with RGB values, I am using yellow here
Set xLastRng = Target

End Sub
This comment was minimized by the moderator on the site
work.... great...
This comment was minimized by the moderator on the site
Yes, I would like to know this as well. How would you keep the previously selected cells highlight for tracking purposes?
This comment was minimized by the moderator on the site
See my comment above.
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