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

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

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

doc зберегти колір лінії сітки 1

Зберегти лінії сітки, заповнюючи колір кодом VBA


стрілка синя права міхур Зберегти лінії сітки, заповнюючи колір кодом VBA

Зазвичай ми не можемо прямо вирішити цю роботу, але тут я можу ввести код VBA для вас. Будь ласка, виконайте наступне:

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

2. У лівій Проект-VBAProject на панелі, двічі клацніть ThisWorkbook під розширений VBAProject, потім скопіюйте та вставте наступний код VBA в порожній модуль:

Код VBA: зберегти лінії сітки під час заповнення кольором

Dim xRgPre As Range
Private Sub Workbook_SheetSelectionChange(ByVal Sh As Object, ByVal Target As Range)
    On Error Resume Next
    If Not xRgPre Is Nothing Then DrawBorders xRgPre
    Set xRgPre = Target
End Sub
Private Sub DrawBorders(ByVal Rg As Range)
'Updateby Extendoffice 20160725
    Dim xCell As Range
    Application.ScreenUpdating = False
    For Each xCell In Rg
        If xCell.Interior.ColorIndex = xlNone Then
            With xCell.Borders
                If .ColorIndex = 15 Then
                    .LineStyle = xlNone
                End If
            End With
        Else
            With xCell.Borders
                If .LineStyle = xlNone Then
                    .Weight = xlThin
                    .ColorIndex = 15
                End If
            End With
        End If
    Next
    Application.ScreenUpdating = True
End Sub

doc зберегти колір лінії сітки 2

3. А потім збережіть і закрийте вікно коду, тепер, коли ви заповните колір для діапазону комірок, сітки відображатимуться автоматично.

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

🤖 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 (19)
No ratings yet. Be the first to rate!
This comment was minimized by the moderator on the site
Is this universally and automatically applied to new tables or sheets opened? Or need to do this for each table or sheet you want to have it? How to make it universally and automatically applied to new tables or sheets?
This comment was minimized by the moderator on the site
Simply change MS Office to Open Office...
This comment was minimized by the moderator on the site
Danke für den super Tipp!
This comment was minimized by the moderator on the site
This works great. (Thanks) But here's the real question - Why does Excel allow gridlines to disappear when filling cells with color in the first place? Just another dumb glitch in the techy world that so-called intelligent developers never think of. I mean, the gridlines, by default are supposed to be there anyway...so....
This comment was minimized by the moderator on the site
Thank you! I was pulling hairs trying to get the nice grey-ish borders to stay after colorizing. Can't believe Microsoft hasn't already implemented this.
This comment was minimized by the moderator on the site
Another fix, if you don't want to mess with code:
First figure out which color gray matches the default lines and have it in mind.
In the Home tab click Cell styles, right click on Normal, click Modify -> Format -> Border. For Line Color, select that gray. For Presets, select Outline. Done.
Now you may have to select all (CTRL+A / Command+A) and click Cell styles -> Normal to make sure it's applied to all cells. When you fill a cell, the borders will remain.
This comment was minimized by the moderator on the site
Very helpful- thank you
This comment was minimized by the moderator on the site
This helped me SO much. I have literally been searching so many places and this is the only explanation that worked! Thank you!!!
This comment was minimized by the moderator on the site
Alissa , I had the same problem couldn`t get it fixed but your reply helped me a lot , so thank you very much , you are genius .
This comment was minimized by the moderator on the site
Thank you!!
This comment was minimized by the moderator on the site
Cool, but now if I fill some cells, and hit Ctrl+Z to undo, it won't work. Will not undo.
This comment was minimized by the moderator on the site
Hello, Andrew,
Yes, the above code can not support Undo feature, you should fill no color manually to undo your work.
Thank you!
This comment was minimized by the moderator on the site
use only standard colors ;)
This comment was minimized by the moderator on the site
works but one has to correct the error if you see it.
Dim xRgPre As Range
Private Sub Workbook_SheetSelectionChange(ByVal Sh As Object, ByVal Target As Range)
On Error Resume Next
If Not xRgPre Is Nothing Then DrawBorders xRgPre
Set xRgPre = Target


*************************************
Should READ... as the If statement only ensures that something is there to set to memory allocation.

One could set the next line below for clean up and not allow memory leaks.

Private Sub Workbook_SheetSelectionChange(ByVal Sh As Object, ByVal Target As Range)
On Error Resume Next
Set xRgPre = Target
If Not xRgPre Is Nothing Then DrawBorders xRgPre
'For ensured memory leaks do not happen
'Clean up the memory allocated after it is not needed.
Set xRqPre = Nothing



Have a nice day..
This comment was minimized by the moderator on the site
Does not work with Conditional Formatting. Set xRqPre = Nothing gives error: variable not defined (deleted the line).Screen jiggles here too, using 2010. Other wise its a cool tool..
This comment was minimized by the moderator on the site
Works fine, but sadly every time I now click on a cell, the worksheet judders! Removed the VBA and the judder has ceased. Wonder why this should happen?
This comment was minimized by the moderator on the site
Same here with Excel 2016. I'm getting freezing and mostly blanked out screen for several seconds, especially when selecting many cells. It's a shame because it does work perfectly otherwise.
This comment was minimized by the moderator on the site
Hi, Vic,
There is no this problem in my Excel workbook, which Excel version do you use?
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