Excel vba цвет текста

VBA text box font color

I’m helping update Excel templates at my work and I need some help. I’m trying to format text in a textbox to be red and remove the border. I’m not sure how to add that property to my code. I’m not very good at coding. I was able to put the below together from dissecting other code I found.

I’ll eventually replace the absolute location values in the textbox code but I want it to work before I start making efficiency tweaks. Thanks for helping!

EDIT1: The below code works if I use either line 1 and 2 or Line 1 and 3. I’m not sure why I cannot use both in conjuction.

1 Answer 1

@ L L The way you are doing it with shapes.addtextbox do it like this:

If I keep typing in the text box then the rest is wrapped in red as well as whatever was in there with the first assignment, the command button in the screenshot executes the code above just to play around.

If you are going to keep adding and subtracting text to the textbox with code it is better if you get the shape named. Then you can grab the string that is in there and add to it . . This code below shows how you can name and then play around with your text box using VBA, adding text and so forth . . you can now change the color of certain text within the textbox as well, which is cool but another topic maybe?

So I hope this helps. The easiest way out if you have the developer tab is to add an ActiveX textbox (you will not be able to use .characters I don’t think) but you can assign the textbox name and many properties: text font, size, color (.forecolor) of that text box right in the properties tab or in vba as well with the name (easy to make all one color, hard to change only selected text in the textbox to a certain color in VBA this way), but for the whole box? easy.

If you do it this way and want to grab the contents of the textbox in vba, lets say you Dim a a comment string in your code and you name your activeX textbox TextBox1:

you have to use the first way of inserting a textbox (the way you are currently using and the first way in the answer) to change only selected text to a new color as far as I have found. Want to see it in action? Add this code below what is above but just before End Sub, now what was there previously is red, the string you define in the code block will be blue if found, in this case I lazily assign it to newText

I sincerely hope this helps you in your search of being a textBox jedi! Cheers – WWC

Источник: stackoverflow.com

Свойство Font. Color (Excel) Font.Color property (Excel)

Возвращает или задает основной цвет объекта, как показано в таблице в разделе “Примечания”. Returns or sets the primary color of the object, as shown in the table in the remarks section. Используйте функцию RGB для создания значения цвета. Use the RGB function to create a color value. Для чтения и записи, Variant. Read/write Variant.

Синтаксис Syntax

Expression. Color (цвет ) expression.Color

Expression (выражение ) Выражение, возвращающее объект Font . expression An expression that returns a Font object.

Примечания Remarks

Object Object Цвет Color
Border Border Цвет границы. The color of the border.
Borders Borders Цвет всех четырех границ диапазона. The color of all four borders of a range. Если они не имеют одинаковый цвет, то Color возвращает 0 (ноль). If they’re not all the same color, Color returns 0 (zero).
Font Font Цвет шрифта. The color of the font.
Interior Interior Цвет заливки ячейки или цвет заливки графического объекта. The cell shading color or the drawing object fill color.
Tab Tab Цвет вкладки. The color of the tab.

Пример Example

В этом примере показано, как задать цвет подписей делений на оси значений в диаграммы Chart1. This example sets the color of the tick-mark labels on the value axis on Chart1.

Поддержка и обратная связь Support and feedback

Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Have questions or feedback about Office VBA or this documentation? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь. Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.

Источник: docs.microsoft.com

VBA Excel. Цвет текста в ячейке

Изменение цвета текста (шрифта) в ячейке рабочего листа Excel с помощью кода VBA. Свойства .Font.Color, .Font.ColorIndex и .Font.TintAndShade

Использование цветовой палитры для присвоения цвета тексту в ячейке листа Excel аналогично присвоению цвета фону ячейки, только свойство диапазона .Interior меняем на свойство .Font.

Цвет текста и предопределенные константы

Цвет шрифту в ячейке можно присвоить с помощью предопределенных констант:

Напомню, что вместо индексов строк и столбцов можно использовать переменные. Список предопределенных констант смотрите здесь.

Цвет шрифта и модель RGB

Для изменения цвета текста в ячейке можно использовать цветовую модель RGB:

Аргументы функции RGB могут принимать значения от 0 до 255. Если все аргументы равны 0, цвет – черный, если все аргументы равны 255, цвет – белый. Функция RGB преобразует числовые значения основных цветов (красного, зеленого и синего) в индекс основной палитры.

Свойство .Font.ColorIndex

Свойство .Font.ColorIndex может принимать значения от 1 до 56. Это стандартная ограниченная палитра, которая существовала до Excel 2007 и используется до сих пор. Посмотрите примеры:

Таблица соответствия значений ограниченной палитры цвету:

Открывается в новом окне Стандартная палитра Excel из 56 цветов

Основная палитра

Основная палитра, начиная c Excel 2007, состоит из 16777216 цветов. Свойство .Font.Color может принимать значения от 0 до 16777215, причем 0 соответствует черному цвету, а 16777215 – белому.

Отрицательные значения свойства .Font.Color

При записи в Excel макрорекордером макроса с присвоением шрифту цвета используются отрицательные значения свойства .Font.Color, которые могут быть в пределах от -16777215 до -1. Отрицательные значения соответствуют по цвету положительному значению, равному сумме наибольшего индекса основной палитры и данного отрицательного значения. Например, отрицательное значение -8257985 соответствует положительному значению 8519230, являющегося результатом выражения 16777215 + (-8257985). Цвета текста двух ячеек из следующего кода будут одинаковы:

Свойство .Font.TintAndShade

Еще при записи макроса с присвоением шрифту цвета макрорекордером добавляется свойство .Font.TintAndShade, которое осветляет или затемняет цвет и принимает следующие значения:

  • -1 – затемненный;
  • – нейтральный;
  • 1 – осветленный.

При тестировании этого свойства в Excel 2016, сравнивая затемненные и осветленные цвета, разницы не заметил. Сравните сами:

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

Источник: webhamster.ru

(VBA Excel) Цвет текста примечания

Visual Basic
10.05.2017, 12:22

VBA-Excel Вытащить рисунок из примечания
Дорого времени суток Есть файлик в одном из столбцов в примечаниях находятся рисунки Задача.

Excel Vba – замена текста по условию
Задача: в строке, где встречается слово “ПЕНИЕ” заменить пустые ячейки на другой текст, например.

Перемещение текста закладок из Word в Excel, VBA
Мне нужно переместить текст закладок из Word в определенные ячейки Excel. Пока получается.

Поиск и номер позиции текста в VBA (Excel)
Привет всем.. У меня тут такое дело, например в ячейке A1 есть следующие данные: Cabinet No.=0.

10.05.2017, 13:03 2

Решение

Visual Basic
10.05.2017, 14:46 [ТС] 3
10.05.2017, 14:46
10.05.2017, 14:46

Заказываю контрольные, курсовые, дипломные и любые другие студенческие работы здесь.

Форматирование примечания в Excel
Доброго времени суток всем. Очень нужна помощь! Имеется таблица примерно с 60 000 ячеек и у.

Форматирование примечания и текста
Имеется код: ThisWorkbook.Sheets(“Калькулятор”).Cells(j + 2, 3) = TestTable5(j + 4, 2) ‘ Название.

VBA – потеря текста при импорте из excel в access
Добрый день, уважаемые Форумчане! В Access делаю функцию которая будет обновлять базу данных на.

Текст Примечания в переменную Excel
Добрый вечер! Как поместить в Переменную содержимое Примечания. Спасибо.

Источник: www.cyberforum.ru

VBA Font Color

VBA Font Color

VBA has a lot of commands and functions to play with. We can do anything in VBA and apply that to Excel. Applying VBA in Excel is the easiest and a fun thing. VBA also has the function by which we can change the color of cell, fonts and we can even bold the characters as well. VBA font color is used in different ways and it helps to change the color of the fonts in excel.

How to Color a Font Using VBA?

Let’s see the examples of font color in Excel VBA.

Valuation, Hadoop, Excel, Mobile Apps, Web Development & many more

Example #1 – VBA Font Color

We have sample text in an Excel sheet with the text “VBA Font Color” in cell B3 as shown below. As we can see the color of the font is default black color in nature.

To apply the VBA code for changing the color of fonts for above-shown text, we need a module.

Step 1: So for this go to the VBA window and click on Module option available in the Insert menu option as shown below.

Step 2: Once we do that, we will get the blank window of Module. In that, start writing subcategory of VBA Font Color or in any other name as per your need as shown below.

Code:

Step 3: First select the range of the cell where the text is located. Here, our range will be cell B3 and that will be written followed by “.Select” command as shown below.

Code:

Step 4: As we need to change the color of fonts so we will select the Font command with the help of Selection as shown below.

Code:

Step 5: After that, we will select the command Color separated by a dot (.) as shown below.

Code:

Now to understand the formation of any color, in VBA we have RGB i.e. Red-Green-Blue. Numeric values of each color range from 0 to 255. Suppose we need to change to a color font to Black then RGB value will be RGB(0, 0, 0). As we already have the black color font we will try to select some other color.

Step 6: Let’s give the largest value to Green color and least to Red and zero to Blue color. As per that, considering Red at 20, Green at 230 and Blue at zero as shown below.

Code:

Step 7: Now compile the code to find if it has any error and then run by clicking on the play button located below the menu bar. We will apply font color for text which is in cell B3 and now changed from Black to Green color.

Example #2 – VBA Font Color

There is another way of changing the font color in VBA. For this, we will consider the same text as shown in example-1 located in cell B3.

Apart from RGB, we can change the color of fonts with the keyword “vb” followed by the name of the color. But by this process, we can only get the main basic color as the font color. Where with the help of RGB we could get color of any shade, just by putting the different values for Red, Green and Blue colors.

The color which can be used with vb are Black, Blue, Cyan, Green, Magenta, Red, White, and Yellow. And how to select the color in format is shown below.

Step 1: To apply this, go to VBA to create the subcategory in the name of VBA Font Color or in any other name in a new module as shown below.

Code:

Step 2: Select the range of cell for which we need to change the font color as shown below.

Code:

Step 3: In the same manner what we have seen in example-1, use selection function with Font and Color to activate them.

Code:

Step 4: It lets the color of font from Black to Cyan. For this select Cyan color by vbCyan as shown below.

Code:

Step 5: If required then we can compile the code and then run it. We will see the font color of text at cell B3 is changed from Black to Cyan.

Example #3 – VBA Font Color

Microsoft has defined a variety of color in different numbers. These are 56 in numbers. We can select any of the color code between to 1 to 56 to change the font color of any cell. These color codes are shown below.

Step 1: Now go to the VBA window and open a new module. In that write the Sub Category of VBA Font Color as shown below.

Code:

Step 2: For this example, we will select the same text as seen in the above examples. Now select the range of the cell which is B3 as shown below.

Code:

Step 3: Now in the second line, select the Font function with Selection command.

Code:

Step 4: To select and apply the above-shown color code, we need to select ColorIndex function instead of Color which we used in example 1 and 2.

Code:

And at last, select the color code which we need to see in a selected range of cell. Let’s select color code 46 which is used for Orange color.

Step 5: Now run the code to see the change. We will the color font at cell B3 is now changed from black to orange.

Pros of VBA Font Color

  • It is easy to implement.
  • With the help of RGB, we can change the color of any shade we want.
  • It helps in creating the dashboard where we need to show the different types of data in a different color with the help of VBA.

Things to Remember

  • It is always recommended to use RGB when we do not know the color code. By giving a different color range from 0 to 255 in RGB we can create any color from dark to bright shade of our choice.
  • Saving the file in Macro Enable Excel helps to use and visit the written code multiple times.
  • Although changing font color in excel is the easiest way to do, but automating this activity in huge set of work can save the time and it will avoid the chances when the file may get crash or hang.

Recommended Articles

This is a guide to VBA Font Color. Here we discuss how to use Excel VBA Font Color along with few practical examples and downloadable excel template. You can also go through our other suggested articles –

Источник: www.educba.com

sitesaid.ru

Создание сайта

Управление цветом в Visual Basic 6.0

Справочные данные Visual Basic 6.0
Поэтапное создания программ
Элементы программирования
Основы программирования

Для настройки цвета фона формы и расположенных в форме элементов можно использовать диалоговое окно настройки цветовой палитры .

Для вызова этого диалогового окна необходимо заменить код в событии click кнопки cbcontrol приложения MySmallProject на следующий:

Private Sub cbControl_Click()
cdlMyDialog.ShowColor
End Sub

Расширенное диалоговое окно настройки цветовой палитры можно создать с помощью объекта CommonDialog.

Значения для метода Flags диалогового окна цветовой палитры
Константа Значение Описание
cdlCCFullOpen &H2 Помещает в диалоговое окно дополнительную кнопку “Добавить в набор” и цветовое поле с маркером и линейкой назначения оттенка для добавления цветов в поля “Дополнительные цвета” диалогового окна цветовой палитры
cdlCCShowHelp &H8 Добавляет в диалоговое окно кнопку “Справка”
cdlCCPreventFullOpen &H4 Скрывает кнопку “Добавить в набор”
cdlCCRGBInit &H1 Восстанавливает в диалоговом окне исходный набор цветов
Функции цвета

Функция RGB возвращает числовое представление цвета (тип возвращаемого значения при этом long) в соответствии с интенсивностью трех цветовых составляющих:
R (Red— красный),
G (Green — зеленый)
В (Blue — синий).
Интенсивность этих трех основных цветов задается шкалой чисел от О до 255. Синтаксис этой функции такой:
RGB (Red, Green, Blue)
где:
Red — интенсивность красного цвета от 0 до 255;
Green — интенсивность зеленого цвета от 0 до 255;
Blue — интенсивность синего цвета от 0 до 255.
Для примера в табл. 11.2 показаны часто используемые цвета, разложенные по интенсивностям RGB-цветов.

Цвета в RGB-представлении
Цвет Интенсивность красного Интенсивность зеленого Интенсивность синего
Черный
Белый 255 255 255
Красный 255
Зеленый 255
Синий 255
Пурпурный 255 255
Желтый 255 255
Серый 192 192 192

Чтобы сделать фон формы например синим, необходимо установить в свойстве BackColor формы следующее значение: Form.BackColor = RGB (0,0,255) Функция QBColor предназначена для облегчения работы о стандартными цветами, возвращающая числовое представление одного из цветов, показанных в таблице.

Цвета, возвращаемые функцией QBColor

Номер цвета Цвет
Черный
1 Синий
2 Зеленый
3 Бирюзовый
4 Красный
5 Пурпурный
6 Желтый
7 Белый
8 Серый
9 Светло-синий (голубой)
10 Светло-зеленый (салатный)
11 Светло-бирюзовый
12 Светло-красный (алый)
13 Светло-пурпурный
14 Светло-желтый
15 Ярко-белый

Синтаксис этой функции:
QBColor (NumberColor)
где NumberColor — числовое значение (номер цвета).
Чтобы установить для формы к примеру синий цвет фона надо написать следующий код:
Form.BackColor = QBColor(1)

Управление цветом

Цвет формы и элементов управления устанавливаются свойствами ForeColor и BackColor. Свойство ForeCoior задает цвет текста, а BackColor устанавливает цвет фона.

Во время разработки приложения эти свойства можно установить в окне Properties (Свойства) объекта, вызвав диалоговое окно настройки цвета.

Для этого необходимо выделить свойство и нажать на кнопку со стрелкой в правом столбце свойства. Как видно из рисунка, это диалоговое окно состоит из двух вкладок: Palette (Палитра) и System (Системные).

На вкладке Palette можно установить произвольные цвета из палитры, на вкладке System можно выбрать цвет из списка цветовой схемы Windows, которая устанавливается в панели управления Windows вызовом окна настройки Свойства: Display. При использовании цветовой схемы необходимо иметь в виду, что при изменении настройки цветовой схемы Windows соответственно изменятся и цвета приложения.

В режиме выполнения приложения свойства ForeColor и BackColor можно установить простым присвоением, используя функции цвета или встроенные константы Visual Basic

Источник: sitesaid.ru

Добавить комментарий

Adblock
detector