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

Как изменить цвет вкладки листа в зависимости от значения ячейки?

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

Изменить цвет вкладки одного листа на основе значения ячейки с кодом VBA

Измените несколько вкладок листов на основе значения ячейки с кодом VBA


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

Например, я хочу, чтобы текущий цвет вкладки листа был зеленым, если значением ячейки в A1 является текст «ИСТИНА», цвет вкладки будет красным, если текст в A1 - «ЛОЖЬ», и цвет вкладки будет синим, если значение в ячейке A1 - это любой другой текст, как показано на следующем снимке экрана:

цветной лист документа по значению 1

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

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

Код VBA: изменение цвета вкладки одного листа в зависимости от значения ячейки:

Private Sub Worksheet_Change(ByVal Target As Range)
'Updateby Extendoffice
    If Target.Address = "$A$1" Then
        Select Case Target.Value
        Case "False"
            Me.Tab.Color = vbRed
        Case "True"
            Me.Tab.Color = vbGreen
        Case Else
            Me.Tab.Color = vbBlue
        End Select
    End If
End Sub

цветной лист документа по значению 2

Примечание: В приведенном выше коде A1 это ссылка на ячейку, по которой вы хотите раскрасить вкладку, "Правда","Ложь»- это текст, который вам нужен, вы можете изменить его по своему усмотрению, и вы можете изменить цвет в коде по своему усмотрению.

3. Затем сохраните и закройте это окно кода, теперь, когда вы вводите текст «True» в ячейку A1, цвет текущей вкладки станет зеленым, а когда вы введете текст «False» в ячейку A1, цвет вкладки станет красным, а если в ячейку A1 ввести другой текст, цвет табуляции автоматически станет синим.


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

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

1. Удерживайте ALT + F11 , чтобы открыть Microsoft Visual Basic для приложений окно, в открывшемся окне дважды щелкните Эта рабочая тетрадь под ВБАПроект раздел, затем скопируйте и вставьте приведенный ниже код в пустой Модули:

Код VBA: изменение вкладок нескольких листов в зависимости от значения ячейки:

Option Explicit
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
  'Updateby Extendoffice 20160930
  Select Case Sheets("Master").Range("A1").Value
         Case "KTE"
             Sheets("Sheet1").Tab.Color = vbRed
         Case "KTO"
             Sheets("Sheet2").Tab.Color = vbGreen
         Case "KTW"
             Sheets("Sheet3").Tab.Color = vbBlue
         End Select
End Sub

цветной лист документа по значению 3

Примечание: В приведенном выше коде A1 и Master - это ячейка и рабочий лист, на основе которых вы хотите раскрасить вкладку, Sheet1, Sheet2, Sheet3 - это листы, на которых вы хотите раскрасить вкладки. КТЭ, KTW, KTO являются значениями ячеек в A1, на основе которых вы хотите раскрасить вкладки, вы можете изменить ссылки и цвета в коде по своему усмотрению.

2. Затем сохраните и закройте это окно кода, теперь, когда вы вводите текст KTE в ячейку A1 основного листа, вкладка Sheet1 будет окрашена в красный цвет, когда вы введете KTO в ячейку A1, Sheet2 будет окрашен в зеленый цвет, а когда вы вводите KTW в ячейку A1, Sheet3 будет окрашен в синий цвет, см. снимок экрана:

цветной лист документа по значению 4

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

🤖 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
I want every tab to turn Red if G18 is greater than 100. Could someone help me write this code?
This comment was minimized by the moderator on the site
Hello, Lesa,

To modify the code so that when the value in G18 exceeds 100, the color of all worksheet tabs is set to red, you need to implement this functionality in the ThisWorkbook event, not in the Worksheet_Change event of a single worksheet.
1. Open the VBA editor (Alt + F11).
2. In the Project Explorer, find the ThisWorkbook object and double-click to open it.
3. Copy and paste the following code into the code window of ThisWorkbook:
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
    If Not Intersect(Target, Sh.Range("G18")) Is Nothing Then
        Dim ws As Worksheet
        If Sh.Range("G18").Value > 100 Then
            For Each ws In ThisWorkbook.Worksheets
                ws.Tab.Color = RGB(255, 0, 0)
            Next ws
        Else
            For Each ws In ThisWorkbook.Worksheets
                ws.Tab.ColorIndex = xlColorIndexNone
            Next ws
        End If
    End If
End Sub


Result:
If G18 > 100 in any sheet, it iterates through all the worksheets in the workbook, setting their tab color to red.
If the condition is not met, it resets the tab color of all worksheets to the default color.

Please have a try!
This comment was minimized by the moderator on the site
Hi,


I used this code:

Option Explicit
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
'Updateby Extendoffice 20160930
Select Case Sheets("Master").Range("A1").Value
Case "KTE"
Sheets("Sheet1").Tab.Color = vbRed
Case "KTO"
Sheets("Sheet2").Tab.Color = vbGreen
Case "KTW"
Sheets("Sheet3").Tab.Color = vbBlue
End Select
End Sub

The True, False or Else function works for me when I type it manually. However, I have a formula that displays True, False or Else as the result. This formula suddenly causes no response when changing the tab color. The formula is based on another sheet, is this a problem?
This comment was minimized by the moderator on the site
Hello Fabian,

Same problem here, have you found any solution to solve this problem ?

Thanks.
This comment was minimized by the moderator on the site
I have a workbook that has 350+ tabs in it. I would like to change the color of each tab based on information in cell G3 on that individual tab. For example, if cell G3 on sheet 1 = 'Water Production' change the tab to green. Is there a way to do this for every tab without having to each tab individually?
This comment was minimized by the moderator on the site
I want to set the sheet tab color based on the color of cell j4 in each sheet. There are 18+ Tabs and want to update the tab colors when the workbook is opened. If I can’t update when opened I can run the macro after the teams update the sheets.
This comment was minimized by the moderator on the site
Hello, wood
To solve your problem, please apply the below code: (Note: Copy and paste the below code into the ThisWorkbook code mode)
Private Sub Workbook_AfterSave(ByVal Success As Boolean)
Call SetSheetColor
End Sub

Private Sub Workbook_Open()
Call SetSheetColor
End Sub

Private Sub Workbook_SheetActivate(ByVal Sh As Object)
Call SetSheetColor
End Sub

Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
Call SetSheetColor
End Sub

Sub SetSheetColor()
Dim xWShs As Sheets
Dim xRg As Range
Dim xFNum As Integer
Dim xSh As Worksheet
On Error Resume Next
Set xWShs = Application.ActiveWorkbook.Sheets
For xFNum = 1 To xWShs.Count
    Set xSh = xWShs.Item(xFNum)
    Set xRg = xSh.Range("J4")
    xSh.Tab.Color = xRg.Interior.Color
Next
End Sub


https://www.extendoffice.com/images/stories/comments/comment-skyyang/doc-color-sheet.png

Please have a try, hope it can help you!
This comment was minimized by the moderator on the site
I would like my tab to change color if any cell in column O or column P has a value in it. Is this possible?

Thank you!
This comment was minimized by the moderator on the site
Hello ,
I require some help
I need to change the sheet tab color only if in a certain range of cells, has today's date
Say for example,
Column L has some dates in the format (13-May-22)
One of the cell value is today's date, then the tab sheet color should change to red
Please help
Thank you in advance
This comment was minimized by the moderator on the site
Im looking to change to color of the tab based off one of 2 outcomes of a formula I have a formula of=IF((AND(AA1="Occupied",AA2="Occupied",AA3="Occupied",AA4="Occupied")),"Occupied","Vacant")
I need the tab to be red if "Occupied" and green if "Vacant". However the code above in the main post doesn't recognize the output of the If Than
This comment was minimized by the moderator on the site
Hello, Trying to have tab colour change based on value on a seperate sheet called Tracking here is what I tried but it does not seem to be working. Thanks




Private Sub Worksheet_Change(ByVal Target As Range)

'Updateby Extendoffice 20160930

If Target.Address = "Tracking!$C$2" Then

Select Case Target.Value

Case "ip"

Me.Tab.Color = vbRed

Case "w"

Me.Tab.Color = vbYellow

Case "c"

Me.Tab.Color = vbGreen

Case Else

Me.Tab.Color = vbBlue

End Select

End If

End Sub
This comment was minimized by the moderator on the site
Hello, Brad,
To make the code run correctly, you should not insert the sheet name into the code, please apple the following code:(click the sheet name you want to run this code, and then right clik the sheet name, and choose View Code, then paste the code into the module)

Private Sub Worksheet_Change(ByVal Target As Range)

'Updateby Extendoffice 20160930

If Target.Address = "$C$2" Then

Select Case Target.Value

Case "ip"

Me.Tab.Color = vbRed

Case "w"

Me.Tab.Color = vbYellow

Case "c"

Me.Tab.Color = vbGreen

Case Else

Me.Tab.Color = vbBlue

End Select

End If

End Sub

Please try, hope it can help you!
This comment was minimized by the moderator on the site
Hello,

Never done code in excel before. I need a code that do what this code do, but I need another parameter.

So what I need is:

If cell value is not 0, and/or if some other cell has numbers in it, using count, then change color to red

If cell value is 0 and those other cells are empty, using count, then change color to green
This comment was minimized by the moderator on the site
How would you link the tab to a value in a different tab. In my example I have one tab with all the information that filters out to various tabs automatically. However each tab will read green or red, depending on whether there is a bAlance outstanding on the master tab. Can this be done using this code and if so, where do I write the link to the master sheet within this code?
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