Excel vba colour no fill in

What This VBA Code Does

The following line of VBA code will allow you to determine if a spreadsheet cell has a fill color. If the ColorIndex property of a given cell is equal to xlNone (-4142) then it can be determined that there is no fill color in that particular cell.

Consequently, you can also remove a cell’s fill color by setting the ColorIndex property equal to xlNone.

VBA Code Example:

Here is an example code snippet where the macro loops through all cells in a given selection and writes the color code of the fill color only for cells that have a fill color to begin with.

Using VBA Code Found On The Internet

Now that you’ve found some VBA code that could potentially solve your Excel automation problem, what do you do with it? If you don’t necessarily want to learn how to code VBA and are just looking for the fastest way to implement this code into your spreadsheet, I wrote an article (with video) that explains how to get the VBA code you’ve found running on your spreadsheet.

Getting Started Automating Excel

Are you new to VBA and not sure where to begin? Check out my quickstart guide to learning VBA. This article won’t overwhelm you with fancy coding jargon, as it provides you with a simplistic and straightforward approach to the basic things I wish I knew when trying to teach myself how to automate tasks in Excel with VBA Macros.

Also, if you haven’t checked out Excel’s latest automation feature called Power Query, I have put together a beginner’s guide for automating with Excel’s Power Query feature as well! This little-known built-in Excel feature allows you to merge and clean data automatically with little to no coding!

How Do I Modify This To Fit My Specific Needs?

Chances are this post did not give you the exact answer you were looking for. We all have different situations and it’s impossible to account for every particular need one might have. That’s why I want to share with you: My Guide to Getting the Solution to your Problems FAST! In this article, I explain the best strategies I have come up with over the years to get quick answers to complex problems in Excel, PowerPoint, VBA, you name it

I highly recommend that you check this guide out before asking me or anyone else in the comments section to solve your specific problem. I can guarantee that 9 times out of 10, one of my strategies will get you the answer(s) you are needing faster than it will take me to get back to you with a possible solution. I try my best to help everyone out, but sometimes I don’t have time to fit everyone’s questions in (there never seem to be quite enough hours in the day!).

I wish you the best of luck and I hope this tutorial gets you heading in the right direction!

Chris
Founder, TheSpreadsheetGuru.com

Changing background colors in Excel VBA is easy. Use the Interior property to return an Interior object. Then use the ColorIndex property of the Interior object to set the background color of a cell.

Place three command buttons on your worksheet and add the following code lines:

1. The code line below sets the background color of cell A1 to light blue.

Range(«A1»).Interior.ColorIndex = 37

Result:

Background Color in Excel VBA

2. The following code line sets the background color of cell A1 to ‘No Fill’.

Range(«A1»).Interior.ColorIndex = 0

Result:

No Fill

3. If you want to know the ColorIndex number of a color, simply ask Excel VBA.

MsgBox Selection.Interior.ColorIndex

Select cell A1 and click the command button on the sheet:

Get ColorIndex Number

Result:

ColorIndex Number

4. The ColorIndex property gives access to a color palette of 56 colors.

Color Palette

Note: download the Excel file to see how we created this color palette.

5. If you can’t find the specific color you are looking for, use the Color property and the RGB function.

Range(«A1»).Interior.Color = RGB(255, 0, 0)

Explanation: RGB stands for Red, Green and Blue. These are the three primary colors. Each component can take on a value from 0 to 255. With this function you can make every color. RGB(255,0,0) gives the pure Red color (ColorIndex = 3 produces the exact same result).

Содержание

  1. Background Colors
  2. VBA Vault
  3. VBA To Determine If Cell Has No Fill Color
  4. What This VBA Code Does
  5. VBA Code Example:
  6. Using VBA Code Found On The Internet
  7. Getting Started Automating Excel
  8. How Do I Modify This To Fit My Specific Needs?
  9. VBA Vault
  10. VBA Code To Remove Cell Fill Colors
  11. What This VBA Code Does
  12. Remove All Cell Fill Colors
  13. Modify To Be More Specific
  14. Change One Color To Another
  15. Using VBA Code Found On The Internet
  16. Getting Started Automating Excel
  17. How Do I Modify This To Fit My Specific Needs?
  18. VBA Excel. Цвет ячейки (заливка, фон)
  19. Свойство .Interior.Color объекта Range
  20. Заливка ячейки цветом в VBA Excel
  21. Вывод сообщений о числовых значениях цветов
  22. Использование предопределенных констант
  23. Цветовая модель RGB
  24. Очистка ячейки (диапазона) от заливки
  25. Свойство .Interior.ColorIndex объекта Range
  26. 86 комментариев для “VBA Excel. Цвет ячейки (заливка, фон)”

Background Colors

Changing background colors in Excel VBA is easy. Use the Interior property to return an Interior object. Then use the ColorIndex property of the Interior object to set the background color of a cell.

Place three command buttons on your worksheet and add the following code lines:

1. The code line below sets the background color of cell A1 to light blue.

2. The following code line sets the background color of cell A1 to ‘No Fill’.

3. If you want to know the ColorIndex number of a color, simply ask Excel VBA.

Select cell A1 and click the command button on the sheet:

4. The ColorIndex property gives access to a color palette of 56 colors.

Note: download the Excel file to see how we created this color palette.

5. If you can’t find the specific color you are looking for, use the Color property and the RGB function.

Explanation: RGB stands for Red, Green and Blue. These are the three primary colors. Each component can take on a value from 0 to 255. With this function you can make every color. RGB(255,0,0) gives the pure Red color (ColorIndex = 3 produces the exact same result).

Источник

VBA Vault

An Excel, PowerPoint, & MS Word blog providing handy and creative VBA code snippets. These macro codes are well commented and are completely functional when copied into a module.

VBA To Determine If Cell Has No Fill Color

What This VBA Code Does

The following line of VBA code will allow you to determine if a spreadsheet cell has a fill color. If the ColorIndex property of a given cell is equal to xlNone (-4142) then it can be determined that there is no fill color in that particular cell.

‘Test if cell has a fill color
If ActiveCell.Interior.ColorIndex <> xlNone Then

Consequently, you can also remove a cell’s fill color by setting the ColorIndex property equal to xlNone.

‘Remove Fill Color
ActiveCell.Interior.ColorIndex = xlNone

VBA Code Example:

Here is an example code snippet where the macro loops through all cells in a given selection and writes the color code of the fill color only for cells that have a fill color to begin with.

Sub TestFillColor()
‘PURPOSE: Write color code to cell only if there is a fill color
‘SOURCE: www.thespreadsheetguru.com/the-code-vault

Dim cell As Range

‘Loop through each cell in selected range
For Each cell In Selection.Cells

‘Test if cell has a fill color
If cell.Interior.ColorIndex <> xlNone Then

‘Write color code to cell value
cell.Value = cell.Interior.Color

Using VBA Code Found On The Internet

Now that you’ve found some VBA code that could potentially solve your Excel automation problem, what do you do with it? If you don’t necessarily want to learn how to code VBA and are just looking for the fastest way to implement this code into your spreadsheet, I wrote an article (with video) that explains how to get the VBA code you’ve found running on your spreadsheet.

Getting Started Automating Excel

Are you new to VBA and not sure where to begin? Check out my quickstart guide to learning VBA. This article won’t overwhelm you with fancy coding jargon, as it provides you with a simplistic and straightforward approach to the basic things I wish I knew when trying to teach myself how to automate tasks in Excel with VBA Macros.

Also, if you haven’t checked out Excel’s latest automation feature called Power Query, I have put together a beginner’s guide for automating with Excel’s Power Query feature as well! This little-known built-in Excel feature allows you to merge and clean data automatically with little to no coding!

How Do I Modify This To Fit My Specific Needs?

Chances are this post did not give you the exact answer you were looking for. We all have different situations and it’s impossible to account for every particular need one might have. That’s why I want to share with you: My Guide to Getting the Solution to your Problems FAST! In this article, I explain the best strategies I have come up with over the years to get quick answers to complex problems in Excel, PowerPoint, VBA, you name it!

I highly recommend that you check this guide out before asking me or anyone else in the comments section to solve your specific problem. I can guarantee that 9 times out of 10, one of my strategies will get you the answer(s) you are needing faster than it will take me to get back to you with a possible solution. I try my best to help everyone out, but sometimes I don’t have time to fit everyone’s questions in (there never seem to be quite enough hours in the day!).

I wish you the best of luck and I hope this tutorial gets you heading in the right direction!

Источник

VBA Vault

An Excel, PowerPoint, & MS Word blog providing handy and creative VBA code snippets. These macro codes are well commented and are completely functional when copied into a module.

VBA Code To Remove Cell Fill Colors

What This VBA Code Does

Here is a simple VBA macro that will remove any fill colors from your selected cell range. While this may be straightforward, it can help guide you with more complicated variations that you may be trying to code such as turning blue fill colors into green.

Remove All Cell Fill Colors

This VBA macro code removes any fill color from the user’s cell selection.

Sub RemoveAllFillColors()
‘PURPOSE: Remove any Fill Colors from Selected Cell Range
‘SOURCE: www.TheSpreadsheetGuru.com/the-code-vault

‘Optimize Code
Application.ScreenUpdating = False

‘Ensure Cell Range Is Selected
If TypeName(Selection) <> «Range» Then
MsgBox «Please select some cells before running»
Exit Sub
End If

‘Remove Any Fill Colors From Selected Cells
Selection.Interior.Color = xlNone

Modify To Be More Specific

Here is a variation on the previous VBA code that only removes the cell fill from spreadsheet cells that have a white colored fill.

Sub RemoveWhiteFillColor()
‘PURPOSE: Remove White Fill from Selected Cells
‘SOURCE: www.TheSpreadsheetGuru.com/the-code-vault

Dim cell As Range

‘Optimize Code
Application.ScreenUpdating = False

‘Ensure Cell Range Is Selected
If TypeName(Selection) <> «Range» Then
MsgBox «Please select some cells before running»
Exit Sub
End If

‘Loop Through Each Cell
For Each cell In Selection.Cells
If cell.Interior.Color = vbWhite Then
cell.Interior.Color = xlNone
End If
Next

Change One Color To Another

Here is another modification idea you can do by searching for a specific color and turning it into another fill color.

Sub WhiteFill_To_BlueFill()
‘PURPOSE: Change any cell with a white fill color to a blue fill color
‘SOURCE: www.TheSpreadsheetGuru.com/the-code-vault

Dim cell As Range

‘Optimize Code
Application.ScreenUpdating = False

‘Ensure Cell Range Is Selected
If TypeName(Selection) <> «Range» Then
MsgBox «Please select some cells before running»
Exit Sub
End If

‘Loop Through Each Cell
For Each cell In Selection.Cells
If cell.Interior.Color = vbWhite Then
cell.Interior.Color = RGB(0, 0, 255)
End If
Next

I want to give a special thank you to Robert D. from my Email Newsletter for coming up with this post idea and helping write some of the VBA code!

Using VBA Code Found On The Internet

Now that you’ve found some VBA code that could potentially solve your Excel automation problem, what do you do with it? If you don’t necessarily want to learn how to code VBA and are just looking for the fastest way to implement this code into your spreadsheet, I wrote an article (with video) that explains how to get the VBA code you’ve found running on your spreadsheet.

Getting Started Automating Excel

Are you new to VBA and not sure where to begin? Check out my quickstart guide to learning VBA. This article won’t overwhelm you with fancy coding jargon, as it provides you with a simplistic and straightforward approach to the basic things I wish I knew when trying to teach myself how to automate tasks in Excel with VBA Macros.

Also, if you haven’t checked out Excel’s latest automation feature called Power Query, I have put together a beginner’s guide for automating with Excel’s Power Query feature as well! This little-known built-in Excel feature allows you to merge and clean data automatically with little to no coding!

How Do I Modify This To Fit My Specific Needs?

Chances are this post did not give you the exact answer you were looking for. We all have different situations and it’s impossible to account for every particular need one might have. That’s why I want to share with you: My Guide to Getting the Solution to your Problems FAST! In this article, I explain the best strategies I have come up with over the years to get quick answers to complex problems in Excel, PowerPoint, VBA, you name it!

I highly recommend that you check this guide out before asking me or anyone else in the comments section to solve your specific problem. I can guarantee that 9 times out of 10, one of my strategies will get you the answer(s) you are needing faster than it will take me to get back to you with a possible solution. I try my best to help everyone out, but sometimes I don’t have time to fit everyone’s questions in (there never seem to be quite enough hours in the day!).

I wish you the best of luck and I hope this tutorial gets you heading in the right direction!

Источник

VBA Excel. Цвет ячейки (заливка, фон)

Заливка ячейки цветом в VBA Excel. Фон ячейки. Свойства .Interior.Color и .Interior.ColorIndex. Цветовая модель RGB. Стандартная палитра. Очистка фона ячейки.

Свойство .Interior.Color объекта Range

Начиная с Excel 2007 основным способом заливки диапазона или отдельной ячейки цветом (зарисовки, добавления, изменения фона) является использование свойства .Interior.Color объекта Range путем присваивания ему значения цвета в виде десятичного числа от 0 до 16777215 (всего 16777216 цветов).

Заливка ячейки цветом в VBA Excel

Пример кода 1:

Поместите пример кода в свой программный модуль и нажмите кнопку на панели инструментов «Run Sub» или на клавиатуре «F5», курсор должен быть внутри выполняемой программы. На активном листе Excel ячейки и диапазон, выбранные в коде, окрасятся в соответствующие цвета.

Есть один интересный нюанс: если присвоить свойству .Interior.Color отрицательное значение от -16777215 до -1, то цвет будет соответствовать значению, равному сумме максимального значения палитры (16777215) и присвоенного отрицательного значения. Например, заливка всех трех ячеек после выполнения следующего кода будет одинакова:

Проверено в Excel 2016.

Вывод сообщений о числовых значениях цветов

Числовые значения цветов запомнить невозможно, поэтому часто возникает вопрос о том, как узнать числовое значение фона ячейки. Следующий код VBA Excel выводит сообщения о числовых значениях присвоенных ранее цветов.

Пример кода 2:

Вместо вывода сообщений можно присвоить числовые значения цветов переменным, объявив их как Long.

Использование предопределенных констант

В VBA Excel есть предопределенные константы часто используемых цветов для заливки ячеек:

Предопределенная константа Наименование цвета
vbBlack Черный
vbBlue Голубой
vbCyan Бирюзовый
vbGreen Зеленый
vbMagenta Пурпурный
vbRed Красный
vbWhite Белый
vbYellow Желтый
xlNone Нет заливки

Присваивается цвет ячейке предопределенной константой в VBA Excel точно так же, как и числовым значением:

Пример кода 3:

Цветовая модель RGB

Цветовая система RGB представляет собой комбинацию различных по интенсивности основных трех цветов: красного, зеленого и синего. Они могут принимать значения от 0 до 255. Если все значения равны 0 — это черный цвет, если все значения равны 255 — это белый цвет.

Выбрать цвет и узнать его значения RGB можно с помощью палитры Excel:

Чтобы можно было присвоить ячейке или диапазону цвет с помощью значений RGB, их необходимо перевести в десятичное число, обозначающее цвет. Для этого существует функция VBA Excel, которая так и называется — RGB.

Пример кода 4:

Список стандартных цветов с RGB-кодами смотрите в статье: HTML. Коды и названия цветов.

Очистка ячейки (диапазона) от заливки

Для очистки ячейки (диапазона) от заливки используется константа xlNone :

Свойство .Interior.ColorIndex объекта Range

До появления Excel 2007 существовала только ограниченная палитра для заливки ячеек фоном, состоявшая из 56 цветов, которая сохранилась и в настоящее время. Каждому цвету в этой палитре присвоен индекс от 1 до 56. Присвоить цвет ячейке по индексу или вывести сообщение о нем можно с помощью свойства .Interior.ColorIndex:

Пример кода 5:

Просмотреть ограниченную палитру для заливки ячеек фоном можно, запустив в VBA Excel простейший макрос:

Пример кода 6:

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

Подробнее о стандартной палитре Excel смотрите в статье: Стандартная палитра из 56 цветов, а также о том, как добавить узор в ячейку.

86 комментариев для “VBA Excel. Цвет ячейки (заливка, фон)”

Спасибо, наконец то разобрался во всех перипетиях заливки и цвета шрифта.

Пожалуйста, Виктор. Очень рад, что статья пригодилась.

как проверить наличие фона?

Привет, Надежда!
Фон у ячейки есть всегда, по умолчанию — белый. Отсутствие цветного фона можно определить, проверив, является ли цвет ячейки белым:

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

Привет, Иван!
Посчитать ячейки с одинаковым фоном можно с помощью цикла.
Для реализации этого примера сначала выбираем в таблице ячейку с нужным цветом заливки. Затем запускаем код, который определяет цветовой индекс фона активной ячейки, диапазон таблицы вокруг нее и общее количество ячеек с такой заливкой в таблице.

Каким образом можно использовать не в процедуре, а именно в пользовательской функции VBA свойство .Interior.Color?
Скажем, проверять функцией значение какой-то ячейки и подкрашивать ячейку в зависимости от этого.

Фарин, пользовательская функция VBA предназначена только для возврата вычисленного значения в ячейку, в которой она расположена. Она не позволяет внутри себя менять формат своей ячейки, а также значения и форматы других ячеек.

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

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

Для подкрашивания ячейки в зависимости от ее значения используйте процедуру Sub или штатный инструмент Excel – условное форматирование.

а как можно закрасить только пустые ячейки ?

Лев, закрасить пустые ячейки можно с помощью цикла For Each… Next:

Евгений, спасибо за ссылку на интересный прием.

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

Привет, Александр!
Используйте функцию InStr, чтобы найти положение разделителей, а дальше функции Left и Mid. Смотрите пример с пробелом в качестве разделителя:

Или еще проще с помощью функции Split:

Добрый день!
подскажите, пожалуйста, как можно выводить из таблицы (150 столбцов х 150 строк) адрес ячеек (списком), если они имеют заливку определенного цвета.
Заранее спасибо!

Привет, Валентина!
Используйте два цикла For…Next. Определить числовой код цвета можно с помощью выделения одной из ячеек с нужным цветом.

столбец «D» имеет разноцветную заливку
надо справа от зеленой ячейки написать «Да»

Каким-то образом надо узнать числовое значение цвета, если он не стандартный — vbGreen. Например, можно выделить ячейку с нужным цветом и записать числовое значение цвета в переменную:

Евгений, спасибо за подсказку.
Все получилось

добрый день! подскажите, пожалуйста, как сделать, чтобы результаты выводились на отдельный лист ?
заранее спасибо!

Валентина, замените в коде имя «Лист2» на имя своего листа.

Евгений. Долгое время мучаюсь реализацией следующего сценария: в таблице Excel, которая является базой данных пациентов отделения есть столбец «G» в котором лаборанты отмечают исследования выполненные с контрастом «(С+)» и без «(C-)» и далее в столбце «N» они отмечаются количество использованного контраста «от 50мл до 200мл»; для удобства ввода и уменьшения числа непреднамеренных ошибок в столбцах реализована функция проверки данных что бы сотрудники могли выбирать уже готовые значения из списка и если ошибутся то выскочит ошибка; тем не менее сотрудники умудряются при заполнении таблицы не вносить количество использованного контраста. Вопрос заключается в том, как подкрасить ячейку для ввода количества контраста красным цветом при условии, что в ячейке столбца G фигурирует (С+) с целью акцентировать на этом внимание.
Заранее спасибо за ответ.

Добрый день, Алексей!
Примените условное форматирование:

1 Выберите столбец «N».
2 На вкладке ленты «Главная» перейдите по ссылкам «Условное форматирование» «Создать правило».
3 В открывшемся окне выберите тип правила: «Использовать формулу для определения форматируемых ячеек».
4 В строку формул вставьте =И(ЕСЛИ(G1=»(C+)»;1);ЕСЛИ(N1=»»;1)) . Буква «C» должна быть из одной раскладки (ENG или РУС) в формуле и в ячейке.
5 Нажмите кнопку «Формат» и на вкладке «Заливка» выберите красный цвет.
6 Закройте все окна, нажимая «OK».

Если в ячейке столбца «G» будет выбрано «(С+)», то ячейка той же строки в столбце «N» подкрасится красным цветом. После ввода значения в ячейку столбца «N», ее цвет изменится на первоначальный.

Спасибо Евгений! Ваш пример многое прояснил (в т.ч надо читать Уокенбаха и не филонить). Мне удалось заставить работать этот сценарий не так изящно как у Вас т.е создал для каждой отдельной переменной свое правило: пр. для ГМ. (С+) —> =ЕСЛИ(И(G5066=»ГМ. (С+)»;N5066=»»);»Истина»;»Ложь»)
МТ. (С+) —> =ЕСЛИ(И(G5066=»МТ. (С+)»;N5066=»»);»Истина»;»Ложь») и т.д всего 8 правил для каждого конкретного случая.
И применил их всех для столбца N:N

Ячейку G взял произвольно и в дальнейшем вообще убрал ее на лист метаданных (диапазоны переменных типа ГМ. (С+), МТ. (С+)…)
Еще раз благодарю за помощь! а есть возможность тоже самое сделать цикличным скриптом VBA ? (или я сморозил…).
Заранее спасибо за ответ.

Источник

Заливка ячейки цветом в VBA Excel. Фон ячейки. Свойства .Interior.Color и .Interior.ColorIndex. Цветовая модель RGB. Стандартная палитра. Очистка фона ячейки.

Свойство .Interior.Color объекта Range

Начиная с Excel 2007 основным способом заливки диапазона или отдельной ячейки цветом (зарисовки, добавления, изменения фона) является использование свойства .Interior.Color объекта Range путем присваивания ему значения цвета в виде десятичного числа от 0 до 16777215 (всего 16777216 цветов).

Заливка ячейки цветом в VBA Excel

Пример кода 1:

Sub ColorTest1()

Range(«A1»).Interior.Color = 31569

Range(«A4:D8»).Interior.Color = 4569325

Range(«C12:D17»).Cells(4).Interior.Color = 568569

Cells(3, 6).Interior.Color = 12659

End Sub

Поместите пример кода в свой программный модуль и нажмите кнопку на панели инструментов «Run Sub» или на клавиатуре «F5», курсор должен быть внутри выполняемой программы. На активном листе Excel ячейки и диапазон, выбранные в коде, окрасятся в соответствующие цвета.

Есть один интересный нюанс: если присвоить свойству .Interior.Color отрицательное значение от -16777215 до -1, то цвет будет соответствовать значению, равному сумме максимального значения палитры (16777215) и присвоенного отрицательного значения. Например, заливка всех трех ячеек после выполнения следующего кода будет одинакова:

Sub ColorTest11()

Cells(1, 1).Interior.Color = 12207890

Cells(2, 1).Interior.Color = 16777215 + (12207890)

Cells(3, 1).Interior.Color = 4569325

End Sub

Проверено в Excel 2016.

Вывод сообщений о числовых значениях цветов

Числовые значения цветов запомнить невозможно, поэтому часто возникает вопрос о том, как узнать числовое значение фона ячейки. Следующий код VBA Excel выводит сообщения о числовых значениях присвоенных ранее цветов.

Пример кода 2:

Sub ColorTest2()

MsgBox Range(«A1»).Interior.Color

MsgBox Range(«A4:D8»).Interior.Color

MsgBox Range(«C12:D17»).Cells(4).Interior.Color

MsgBox Cells(3, 6).Interior.Color

End Sub

Вместо вывода сообщений можно присвоить числовые значения цветов переменным, объявив их как Long.

Использование предопределенных констант

В VBA Excel есть предопределенные константы часто используемых цветов для заливки ячеек:

Предопределенная константа Наименование цвета
vbBlack Черный
vbBlue Голубой
vbCyan Бирюзовый
vbGreen Зеленый
vbMagenta Пурпурный
vbRed Красный
vbWhite Белый
vbYellow Желтый
xlNone Нет заливки

Присваивается цвет ячейке предопределенной константой в VBA Excel точно так же, как и числовым значением:

Пример кода 3:

Range(«A1»).Interior.Color = vbGreen

Цветовая модель RGB

Цветовая система RGB представляет собой комбинацию различных по интенсивности основных трех цветов: красного, зеленого и синего. Они могут принимать значения от 0 до 255. Если все значения равны 0 — это черный цвет, если все значения равны 255 — это белый цвет.

Выбрать цвет и узнать его значения RGB можно с помощью палитры Excel:

Палитра Excel

Палитра Excel

Чтобы можно было присвоить ячейке или диапазону цвет с помощью значений RGB, их необходимо перевести в десятичное число, обозначающее цвет. Для этого существует функция VBA Excel, которая так и называется — RGB.

Пример кода 4:

Range(«A1»).Interior.Color = RGB(100, 150, 200)

Список стандартных цветов с RGB-кодами смотрите в статье: HTML. Коды и названия цветов.

Очистка ячейки (диапазона) от заливки

Для очистки ячейки (диапазона) от заливки используется константа xlNone:

Range(«A1»).Interior.Color = xlNone

Свойство .Interior.ColorIndex объекта Range

До появления Excel 2007 существовала только ограниченная палитра для заливки ячеек фоном, состоявшая из 56 цветов, которая сохранилась и в настоящее время. Каждому цвету в этой палитре присвоен индекс от 1 до 56. Присвоить цвет ячейке по индексу или вывести сообщение о нем можно с помощью свойства .Interior.ColorIndex:

Пример кода 5:

Range(«A1»).Interior.ColorIndex = 8

MsgBox Range(«A1»).Interior.ColorIndex

Просмотреть ограниченную палитру для заливки ячеек фоном можно, запустив в VBA Excel простейший макрос:

Пример кода 6:

Sub ColorIndex()

Dim i As Byte

For i = 1 To 56

Cells(i, 1).Interior.ColorIndex = i

Next

End Sub

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

Подробнее о стандартной палитре Excel смотрите в статье: Стандартная палитра из 56 цветов, а также о том, как добавить узор в ячейку.


  • If you would like to post, please check out the MrExcel Message Board FAQ and register here. If you forgot your password, you can reset your password.

  • Thread starter

    haffy311

  • Start date

    Jan 20, 2012

  • #1

Is there VBA color to change «.Fill.ForeColor.SchemeColor =» into NO FILL? In other words, keeping the existing Foreground color prior to the macro being activated.

I’m in a chart.

How to total the visible cells?

From the first blank cell below a filtered data set, press Alt+=. Instead of SUM, you will get SUBTOTAL(9,)

  • #2

Cannot tell what context you are asking the question in. Is this about cells and you don’t want them to be colored by way of their interior color property? If so you can say using A1 for an example…

Range(«A1»).interior.ColorIndex = 0

But maybe you mean something else and maybe not even with cells, and maybe there’s conditonal formatting involved somehow…

Edit, just saw that part about bing in a chart…is it the plot area opr the chart area or something else…just need more info about what you want to manipulate.

Threads
1,192,536
Messages
5,993,056
Members
440,469
Latest member
Quaichlek

Понравилась статья? Поделить с друзьями:
  • Excel vba cell style
  • Excel vba collection dictionary
  • Excel vba cell size
  • Excel vba collapse all
  • Excel vba cell numberformat