Vba excel таблица кодов

Excel Text and String Functions:

Excel CODE & CHAR Functions, VBA Asc & Chr Functions, with examples.

Related Links:

1. Using VBA Chr and Asc functions to convert excel column number to corresponding column letter, and column letter to column number.

2. ASCII Code, Extended ASCII characters (8-bit system) and ANSI Code.

3. Excel Text and String Functions: TRIM & CLEAN.

4. Excel Text and String Functions: LEFT, RIGHT, MID, LEN, FIND, SEARCH, REPLACE, SUBSTITUTE.


Excel CODE Function (Worksheet)

The CODE Function returns the identifying numeric code of the first character in a text string. A ‘character set’ maps characters to their identifying code values, and may vary across operating environments viz. Windows, Macintosh, etc. The Windows operating environment uses the ANSI character set, whereas Macintosh uses the Macintosh character set. The returned numeric code corresponds to this character set — for a Windows computer, Excel uses the standard ANSI character set to return the numeric code. Syntax: CODE(text_string). The text_string argument is the text string whose first character’s numeric code is returned.  

The equivalent of excel CODE function in vba is the Asc function. Note that the Excel CODE function is the inverse of the Excel CHAR function. The formula =CODE(CHAR(65)) returns 65, because =CHAR(65) returns the character «A» and =CODE(«A») returns 65. 

In a Windows computer, Code function will return values as follows:

=CODE(«A») returns 65.

=CODE(«B») returns 66.

=CODE(«a») returns 97.

=CODE(«b») returns 98.

=CODE(«0») returns 48.

=CODE(«1») returns 49.

=CODE(«-1») returns 45, which is the code for «-» (hyphen) .

=CODE(» «) , note the space between inverted commas, returns 32.

=CODE(«»), no space between inverted commas, returns the #VALUE! error value.

=CODE(«America») returns 65, which is the code for «A», the first character in the text string.

=CODE(A1) returns 66, using cell reference. If cell A1 contains the text «Bond», CODE(A1) returns 66, which is the code for «B», the first character in the text string.

=CODE(«?») returns 63.

=CODE(«™») returns 153.


Excel CHAR Function (Worksheet)

Use the CHAR Function to return the character identified to the specified number. A ‘character set’ maps characters to their identifying code values, and may vary across operating environments viz. Windows, Macintosh, etc. The Windows operating environment uses the ANSI character set, whereas Macintosh uses the Macintosh character set. The returned character corresponds to this character set — for a Windows computer, Excel uses the standard ANSI character set. Syntax: CHAR(number). The number argument is a number between 1 and 255 which identifies the returned character. The function returns the #VALUE! error value if this argument is not a number between 1 and 255.

The equivalent of excel CHAR function in vba is the Chr function. Note that the Excel CHAR function is the inverse of the Excel CODE function. The formula =CHAR(CODE(«A»)) returns A, because =CODE(«A») returns the number 65 and =CHAR(65) returns A. 

In a Windows computer, Char function will return values as follows:

=CHAR(65) returns the character «A».

=CHAR(37) returns the character «%».

=CHAR(260) returns the #VALUE! error value.

=CHAR(163) returns the character «£».

=CHAR(A1) returns the character «B», using cell reference. If cell A1 contains the number 66, CHAR(A1) returns the character «B».


Examples of using the Excel CODE & CHAR Functions

Changing case (uppercase / lowercase) of alphabets in a string

Formula  =CHAR(CODE(A1)+32) returns the lowercase letter «b», if cell A1 contains the uppercase letter «B». This is because in the ANSI character set, the lowercase alphabets appear after uppercase alphabets, in an alphabetic order,  with a difference of exactly 32 numbers. Similarly, =CHAR(CODE(A1)-32) returns the uppercase letter «B», if cell A1 contains the lowercase letter «b».

Convert first character of the first word in a text string (consisting of letters), to lowercase, and first character of all subsequent words to uppercase. To convert the string «we like james bond» in cell A1 to «we Like James Bond» use the following formula:

=REPLACE(PROPER(A1), 1,1, CHAR(CODE( LEFT(PROPER(A1)))+32))

=PROPER(A1)   returns the text string «We Like James Bond».

=CHAR(CODE(LEFT( PROPER(A1)))+32)   returns the lowercase text «w».

The formula replaces the first character of the text, by first capitalizing it and then converting it to lowercase using CHAR/CODE functions.

It may however be noted, that the excel UPPER (or LOWER) function can also be used as alternate to CHAR/CODE functions. In this case the Formula  =REPLACE(PROPER(A1),1,1,LOWER(LEFT(PROPER(A1)))) will also give the same result and return the string «we Like James Bond».

—————————————————————————————————————————-

Making the above formula more complex:

Convert first character of the second word in a text string (consisting of letters) to lowercase, and the first character of all other words to uppercase (wherein words are separated by a single space). To convert the string «we Like James bond» in cell A1 to «We like James Bond» use the following formula: 

=REPLACE(PROPER(A1), FIND(» «, A1)+1, 1, CHAR(CODE(MID(PROPER(A1), FIND(» «, A1)+1, 1))+32))

=PROPER(A1)   returns text string «We Like James Bond».

=FIND(» «, A1)+1   returns the position 4.

=MID(PROPER(A1), FIND(» «, A1)+1,1)    returns L.

=CODE(MID(PROPER(A1), FIND(» «, A1)+1,1))    returns 76.

=CHAR(CODE(MID(PROPER(A1), FIND(» «, A1)+1,1))+32)   returns the text «l».

—————————————————————————————————————————  

If a text string has irregular spacing (ie. having lead spaces and multiple spaces between words), insert the TRIM function which removes all spaces from text except for single spaces between words:

=REPLACE(PROPER( TRIM(A1)), FIND(» «, TRIM(A1))+1, 1, CHAR(CODE(MID( PROPER( TRIM(A1)), FIND(» «, TRIM(A1))+1, 1))+32)) 

Note: In addition to the CHAR, CODE, LEFT & MID functions, we have also used the excel worksheet PROPER function. Syntax: PROPER(text).  This function: (i) Capitalizes any letter in a text string which follows a non-letter character, and also the first letter of the text string; (ii) Converts to Lowercase all other letters.

—————————————————————————————————————————

For many letters and controls, it might be much easier to format or otherwise manipulate data with their ANSI codes than using your keyboard.

If the address is currently split in different cells, and you wish to consolidate in a single cell in multiple lines, use the excel CHAR function as follows (refer Image 1):

=A1 & CHAR(10) & B1 & CHAR(10) & C1 & CHAR(10) & D1

The address is currently split in cells A1 to D1 and the above formula consolidates and formats into a single cell in multiple lines.

10 is the ANSI code (number) for line feed, and it provides the line breaks to format data.

Ensure that the cell text wrapping is enabled, by clicking on «Wrap Text».

————————————————————————————————————————-

Format a single line address into multiple lines, using the excel CHAR & SUBSTITUTE functions as follows (refer Image 2):

=SUBSTITUTE(A1,», «,CHAR(10))

The address is currently mentioned in cell A1 in a single line, and the above formula formats it (in cell A3) by removing commas and into multiple lines.

10 is the ANSI code (number) for line feed, and it provides the line breaks to format data.

Ensure that the cell text wrapping is enabled, by clicking on «Wrap Text».

—————————————————————————————————————————

NOTE: To format an address with line breaks (appearing in multiple lines in cell A1) to a single line format (cell A3), use the formula (refer Image 3): =SUBSTITUTE(A1, CHAR(10), «, «) 

——————————————————————————————————————————  

To insert special characters or symbols in a text string, use the excel CHAR function:

=»Exchange Rates Graph of Pound (» & CHAR(163) & «), Euro (» & CHAR(128) & «) and Dollar (» & (CHAR(36) & «)»)

The above formula inserts currency symbols, using the CHAR function.

Returns the text string: «Exchange Rates Graph of Pound (£), Euro(€) and Dollar ($)»


VBA Asc function

The vba Asc function returns the corresponding character code (Integer data type) for the first letter of a string. Syntax: Asc(string). It is necessary to specify the string argument — it is a string expression whose first letter’s character code is returned. You will get a run time error for a string with no characters. For non-DBCS systems the normal range for the returned number is 0 to 255, but on DBCS systems the range is -32768 to 32767.

Use the AscW function to return a Unicode character code, but if the platform does not support Unicode then AscW will give results identical to the Asc function. AscW should not be used in the Macintosh environment because Unicode strings are not supported in Visual Basic for the Macintosh.

VBA Chr function

The vba Chr function returns a character (string data type) identified to the specified character code. Syntax: Chr(charcode). It is necessary to specify the charcode argument — it is the character code (Long data type) which identifies the returned character. The normal range for charcode is 0 to 255, but on DBCS systems (character set that uses 1 or 2 bytes to represent a character, allowing more than 256 characters to be represented — used for languages such as Japanese and Chinese), the actual range for charcode is -32768 to 65535. Numbers from 0 to 31 are the standard ASCII Non-Printing Control Codes.

Use the ChrW function to return a Unicode character, but if the platform does not support Unicode ChrW will give results identical to the Chr function. ChrW should not be used in the Macintosh environment because Unicode strings are not supported in Visual Basic for the Macintosh.

MsgBox Chr(65), returns the letter «A».

MsgBox Asc(«A»), returns the number 65.

—————————————————————————————————————————-  

Sub Chr_Replace()
‘using vba Chr() function to replace characters in a string

Dim str As String

‘replaces letter «A» with «B»

str = Replace(«ABC», Chr(65), Chr(66))

‘returns the text «BBC»

MsgBox str

End Sub

————————————————————————————————————————-  

Sub TextFormat1()
‘using vba chr() function to remove commas and provide line breaks.

‘Chr(10) provides line feed/new line, and it replaces all instances of comma & following space, in the text string. Refer Image 4.
ActiveSheet.Cells(3, 1) = Replace(ActiveSheet.Cells(1, 1), «, «, Chr(10))

End Sub

————————————————————————————————————————————————————  

Sub TextFormat2()
‘inserting symbols using vba chr() function

Dim str As String

‘evaluates to text string «Exchange Rates Graph of Pound (£), Euro (€) and Dollar ($)»
str = «Exchange Rates Graph of Pound (» & Chr(163) & «), Euro (» & Chr(128) & «) and Dollar (» & (Chr(36) & «)«)

‘displays the text string «Exchange Rates Graph of Pound (£), Euro (€) and Dollar ($)»
MsgBox str

End Sub

————————————————————————————————————————————————————  

Sub DeleteSpaces()
‘remove spaces from a text string, in vba, using the vba Replace function

Dim str As String

str = «Removing  Spaces In Text String «

‘removes space character with ANSI code 32

str = Replace(str, Chr(32), «»)

‘returns the text «RemovingSpacesInTextString»

MsgBox str

End Sub

————————————————————————————————————————————————————  

Sub RemoveNumbers()
‘remove characters, say all numericals, from a text string, using the vba Replace function

Dim str As String, i As Integer

str = «RemovingNumbers 12in4 Text6 9String5″
 

‘chr(48) to chr(57) represent numericals 0 to 9 in ANSI/ASCII character codes

For i = 48 To 57

‘remove all numericals from the text string using vba Replace function:

str = Replace(str, Chr(i), «»)

Next i

‘returns text «Removing Numbers in Text String»

MsgBox str

End Sub

————————————————————————————————————————————————————

Sub ManipulateTextString()
‘manipulate text string consisting of only letters & spaces: remove all spaces, separate each word with comma, capitalize first letter of each word & convert all other letters to lowercase

Dim str As String

str = « red   Blue white  GREEN  yellow    «

‘use the worksheet Trim function to remove all spaces from text leaving only single spaces between words — also deletes all leading & trailing spaces

str = Application.Trim(str)

‘replaces space character (ANSI code 32) with comma character (ANSI code 44)

str = Replace(str, Chr(32), Chr(44))

‘use the worksheet Proper function to: Capitalize the first letter & any other letter which follows a non-letter character; also converts to Lowercase all other letters.

str = Application.Proper(str)

‘returns the text «Red,Blue,White,Green,Yellow»

MsgBox str


End Sub

————————————————————————————————————————————————————

VBA Codes:

Using VBA Chr and Asc functions to convert excel column number to corresponding column letter, and column letter to column number.

This page explains how to use Excel VBA ASCFunction to get ASCII value of a text, and how to check if a text contains an alphabet, number or symbol

Excel VBA ASC Function returns the ASCII value of the first character in a text. ASCII (American Standard Code for Information Interchange) uses 8-bit code units, an old encoding system which stores mainly numbers, lowercase letters a to z, uppercase letters A to Z, basic punctuation symbols, control codes. Many old systems still use this encoding system. 8 bit means the computer memory uses “8” digits with 1 and 0 combination (binary) to represent a character, 8 bits memory is equal to 1 byte.

Refer to the below table, Excel ASC Function will convert the “Char” value to “Dec” value.

Dec Hex Oct Char Description
0 0 000 null
1 1 001 start of heading
2 2 002 start of text
3 3 003 end of text
4 4 004 end of transmission
5 5 005 enquiry
6 6 006 acknowledge
7 7 007 bell
8 8 010 backspace
9 9 011 horizontal tab
10 A 012 new line
11 B 013 vertical tab
12 C 014 new page
13 D 015 carriage return
14 E 016 shift out
15 F 017 shift in
16 10 020 data link escape
17 11 021 device control 1
18 12 022 device control 2
19 13 023 device control 3
20 14 024 device control 4
21 15 025 negative acknowledge
22 16 026 synchronous idle
23 17 027 end of trans. block
24 18 030 cancel
25 19 031 end of medium
26 1A 032 substitute
27 1B 033 escape
28 1C 034 file separator
29 1D 035 group separator
30 1E 036 record separator
31 1F 037 unit separator
32 20 040 space
33 21 041 !
34 22 042
35 23 043 #
36 24 044 $
37 25 045 %
38 26 046 &
39 27 047
40 28 050 (
41 29 051 )
42 2A 052 *
43 2B 053 +
44 2C 054 ,
45 2D 055
46 2E 056 .
47 2F 057 /
48 30 060 0
49 31 061 1
50 32 062 2
51 33 063 3
52 34 064 4
53 35 065 5
54 36 066 6
55 37 067 7
56 38 070 8
57 39 071 9
58 3A 072 :
59 3B 073 ;
60 3C 074 <
61 3D 075 =
62 3E 076 >
63 3F 077 ?
64 40 100 @
65 41 101 A
66 42 102 B
67 43 103 C
68 44 104 D
69 45 105 E
70 46 106 F
71 47 107 G
72 48 110 H
73 49 111 I
74 4A 112 J
75 4B 113 K
76 4C 114 L
77 4D 115 M
78 4E 116 N
79 4F 117 O
80 50 120 P
81 51 121 Q
82 52 122 R
83 53 123 S
84 54 124 T
85 55 125 U
86 56 126 V
87 57 127 W
88 58 130 X
89 59 131 Y
90 5A 132 Z
91 5B 133 [
92 5C 134
93 5D 135 ]
94 5E 136 ^
95 5F 137 _
96 60 140 `
97 61 141 a
98 62 142 b
99 63 143 c
100 64 144 d
101 65 145 e
102 66 146 f
103 67 147 g
104 68 150 h
105 69 151 i
106 6A 152 j
107 6B 153 k
108 6C 154 l
109 6D 155 m
110 6E 156 n
111 6F 157 o
112 70 160 p
113 71 161 q
114 72 162 r
115 73 163 s
116 74 164 t
117 75 165 u
118 76 166 v
119 77 167 w
120 78 170 x
121 79 171 y
122 7A 172 z
123 7B 173 {
124 7C 174 |
125 7D 175 }
126 7E 176 ~
127 7F 177 DEL

Extended Character Set

Dec Hex Unicode Open in a new window... Char Zoom... Name
128 80 U+20AC Euro Sign
129 81 Undefined
130 82 U+201A Single Low-9 Quotation Mark
131 83 U+0192 ƒ Latin Small Letter F With Hook
132 84 U+201E Double Low-9 Quotation Mark
133 85 U+2026 Horizontal Ellipsis
134 86 U+2020 Dagger
135 87 U+2021 Double Dagger
136 88 U+02C6 ˆ Modifier Letter Circumflex Accent
137 89 U+2030 Per Mille Sign
138 8A U+0160 Š Latin Capital Letter S With Caron
139 8B U+2039 Single Left-pointing Angle Quotation Mark
140 8C U+0152 Œ Latin Capital Ligature Oe
141 8D Undefined
142 8E U+017D Ž Latin Capital Letter Z With Caron
143 8F Undefined
144 90 Undefined
145 91 U+2018 Left Single Quotation Mark
146 92 U+2019 Right Single Quotation Mark
147 93 U+201C Left Double Quotation Mark
148 94 U+201D Right Double Quotation Mark
149 95 U+2022 Bullet
150 96 U+2013 En Dash
151 97 U+2014 Em Dash
152 98 U+02DC ˜ Small Tilde
153 99 U+2122 Trade Mark Sign
154 9A U+0161 š Latin Small Letter S With Caron
155 9B U+203A Single Right-pointing Angle Quotation Mark
156 9C U+0153 œ Latin Small Ligature Oe
157 9D Undefined
158 9E U+017E ž Latin Small Letter Z With Caron
159 9F U+0178 Ÿ Latin Capital Letter Y With Diaeresis
160 A0 U+00A0   No-break Space
161 A1 U+00A1 ¡ Inverted Exclamation Mark
162 A2 U+00A2 ¢ Cent Sign
163 A3 U+00A3 £ Pound Sign
164 A4 U+00A4 ¤ Currency Sign
165 A5 U+00A5 ¥ Yen Sign
166 A6 U+00A6 ¦ Broken Bar
167 A7 U+00A7 § Section Sign
168 A8 U+00A8 ¨ Diaeresis
169 A9 U+00A9 © Copyright Sign
170 AA U+00AA ª Feminine Ordinal Indicator
171 AB U+00AB « Left-pointing Double Angle Quotation Mark
172 AC U+00AC ¬ Not Sign
173 AD U+00AD ­ Soft Hyphen
174 AE U+00AE ® Registered Sign
175 AF U+00AF ¯ Macron
176 B0 U+00B0 ° Degree Sign
177 B1 U+00B1 ± Plus-minus Sign
178 B2 U+00B2 ² Superscript Two
179 B3 U+00B3 ³ Superscript Three
180 B4 U+00B4 ´ Acute Accent
181 B5 U+00B5 µ Micro Sign
182 B6 U+00B6 Pilcrow Sign
183 B7 U+00B7 · Middle Dot
184 B8 U+00B8 ¸ Cedilla
185 B9 U+00B9 ¹ Superscript One
186 BA U+00BA º Masculine Ordinal Indicator
187 BB U+00BB » Right-pointing Double Angle Quotation Mark
188 BC U+00BC ¼ Vulgar Fraction One Quarter
189 BD U+00BD ½ Vulgar Fraction One Half
190 BE U+00BE ¾ Vulgar Fraction Three Quarters
191 BF U+00BF ¿ Inverted Question Mark
192 C0 U+00C0 À Latin Capital Letter A With Grave
193 C1 U+00C1 Á Latin Capital Letter A With Acute
194 C2 U+00C2 Â Latin Capital Letter A With Circumflex
195 C3 U+00C3 Ã Latin Capital Letter A With Tilde
196 C4 U+00C4 Ä Latin Capital Letter A With Diaeresis
197 C5 U+00C5 Å Latin Capital Letter A With Ring Above
198 C6 U+00C6 Æ Latin Capital Ligature Ae
199 C7 U+00C7 Ç Latin Capital Letter C With Cedilla
200 C8 U+00C8 È Latin Capital Letter E With Grave
201 C9 U+00C9 É Latin Capital Letter E With Acute
202 CA U+00CA Ê Latin Capital Letter E With Circumflex
203 CB U+00CB Ë Latin Capital Letter E With Diaeresis
204 CC U+00CC Ì Latin Capital Letter I With Grave
205 CD U+00CD Í Latin Capital Letter I With Acute
206 CE U+00CE Î Latin Capital Letter I With Circumflex
207 CF U+00CF Ï Latin Capital Letter I With Diaeresis
208 D0 U+00D0 Ð Latin Capital Letter Eth
209 D1 U+00D1 Ñ Latin Capital Letter N With Tilde
210 D2 U+00D2 Ò Latin Capital Letter O With Grave
211 D3 U+00D3 Ó Latin Capital Letter O With Acute
212 D4 U+00D4 Ô Latin Capital Letter O With Circumflex
213 D5 U+00D5 Õ Latin Capital Letter O With Tilde
214 D6 U+00D6 Ö Latin Capital Letter O With Diaeresis
215 D7 U+00D7 × Multiplication Sign
216 D8 U+00D8 Ø Latin Capital Letter O With Stroke
217 D9 U+00D9 Ù Latin Capital Letter U With Grave
218 DA U+00DA Ú Latin Capital Letter U With Acute
219 DB U+00DB Û Latin Capital Letter U With Circumflex
220 DC U+00DC Ü Latin Capital Letter U With Diaeresis
221 DD U+00DD Ý Latin Capital Letter Y With Acute
222 DE U+00DE Þ Latin Capital Letter Thorn
223 DF U+00DF ß Latin Small Letter Sharp S
224 E0 U+00E0 à Latin Small Letter A With Grave
225 E1 U+00E1 á Latin Small Letter A With Acute
226 E2 U+00E2 â Latin Small Letter A With Circumflex
227 E3 U+00E3 ã Latin Small Letter A With Tilde
228 E4 U+00E4 ä Latin Small Letter A With Diaeresis
229 E5 U+00E5 å Latin Small Letter A With Ring Above
230 E6 U+00E6 æ Latin Small Ligature Ae
231 E7 U+00E7 ç Latin Small Letter C With Cedilla
232 E8 U+00E8 è Latin Small Letter E With Grave
233 E9 U+00E9 é Latin Small Letter E With Acute
234 EA U+00EA ê Latin Small Letter E With Circumflex
235 EB U+00EB ë Latin Small Letter E With Diaeresis
236 EC U+00EC ì Latin Small Letter I With Grave
237 ED U+00ED í Latin Small Letter I With Acute
238 EE U+00EE î Latin Small Letter I With Circumflex
239 EF U+00EF ï Latin Small Letter I With Diaeresis
240 F0 U+00F0 ð Latin Small Letter Eth
241 F1 U+00F1 ñ Latin Small Letter N With Tilde
242 F2 U+00F2 ò Latin Small Letter O With Grave
243 F3 U+00F3 ó Latin Small Letter O With Acute
244 F4 U+00F4 ô Latin Small Letter O With Circumflex
245 F5 U+00F5 õ Latin Small Letter O With Tilde
246 F6 U+00F6 ö Latin Small Letter O With Diaeresis
247 F7 U+00F7 ÷ Division Sign
248 F8 U+00F8 ø Latin Small Letter O With Stroke
249 F9 U+00F9 ù Latin Small Letter U With Grave
250 FA U+00FA ú Latin Small Letter U With Acute
251 FB U+00FB û Latin Small Letter U With Circumflex
252 FC U+00FC ü Latin Small Letter U With Diaeresis
253 FD U+00FD ý Latin Small Letter Y With Acute
254 FE U+00FE þ Latin Small Letter Thorn
255 FF U+00FF ÿ Latin Small Letter Y With Diaeresis

Why do you need Excel VBA ASC Function?

The main use of Excel Code Function is to convert alphabet into number. For example, you may want to know if a string contains A to Z, you can simply check if ASCII code is between 65 to 90, same for symbols.

Another use is to check unknown text. Some text looks like a space but underneath it may be something else, which is caused by conversion of other database type to Excel. After checking the ASCII code of that string, you can use Replace function to get rid of it.

Syntax of Excel VBA ASC Function

ASC(text)

Text   The text which you want to convert into ASCII code

Note that ASC Function only returns the ASCII code of the first character in the text.

In Excel worksheet, ASC Function is called Code.

Example of Excel ASC Function

VBA Code Result Explanation
ASC(“A”) 65
ASC(“Z”) 90
ASC(UCASE(Range(“A1”).Value))>=65 AND ASC(UCASE(Range(“A1”).Value))<=90) TRUE (assume A1 contains text “B”) Check if the first text in Cell A1 is an alphabet

Loop through each character in a text to see if the any character contains an alphabet, disregard case sensitivity.

Public Function wCheckAlphabet(var)
    For i = 1 To Len(var)
        If Asc(Mid(UCase(var), i, 1)) >= 65 And Asc(Mid(UCase(var), i, 1)) <= 90 Then
            wCheckAlphabet = True
            Exit Function
        Else
            wCheckAlphabet = False
        End If
    Next i
End Function

Outbound References

https://support.office.microsoft.com/en-us/article/CODE-function-daabc849-79e2-4661-8145-0b33c8397d4b?CorrelationId=2f7d4c56-6976-4a7f-948b-38b2b1da0be1&ui=en-US&rs=en-001&ad=US

excel character map

Often we look to certain symbols in Excel that are hard to locate on the keyboard. Or the opposite – we look to find the Excel character codes for certain characters. In such cases we must usually revert to using the CHAR Excel function or the CODE Excel function. Let us explore these functions and how to use them both in Excel and VBA today.

First let us start with exploring the Excel Character codes.

What is a Character Code? Each character is encoded as a number within a specific character map e.g. in ANSI or UTF8 standard

The table below represent the full default encoding in Excel:
excel character map
On the right side is the Excel character (CHAR) and on the left you have the numeric representation (CODE) of the character.

Converting Characters to Codes (Excel CODE function)

The Excel CODE function allows you to easily obtain the numeric code for the provided character (1 character string).

Syntax

The syntax for the CODE function in VBA is:

CODE( string )

Parameters

string
A single character string.

Example usage

Excel

Below example of using the Excel CODE function:
excel code function

VBA

Below VBA equivalent of the Excel CODE Funtion – the Asc function

Debug.Print Asc("<")
'Result: 60

Converting Codes to Characters (Excel CHAR function)

The Excel CHAR function allows you to easily obtain the character represented by the numeric code.

Syntax

The syntax for the CHAR function in Excel is:

CHAR( number)

Parameters

number
A number from 0-255.

Example usage

Excel

Below example of using the Excel CHAR function:
excel char function

VBA

Below VBA equivalent of the Excel CHAR Funtion – the Chr function:

Debug.Print Chr(60)
'Result: <

Содержание

  • Список кодов индекса цвета VBA
  • Свойство цвета VBA
  • Цвет VB
  • Цвета RGB
  • Список кодов ColorIndex и цвета RGB в Access VBA

При использовании VBA для кодирования Colorindex (или цвета фона) ячейки полезно знать, какое целое число будет равно какому цвету. Ниже приведено справочное изображение, на котором показан цвет и указан соответствующий ему Colorindex. он же Цветовая палитра VBA

Вот код, чтобы сделать его для себя или просто добавить эту страницу в закладки:

123456789101112131415 Sub ColorRef ()Dim x As IntegerДля x = от 1 до 56Если x <ТоCells (x, 1) .Interior.ColorIndex = xЯчейки (x, 2) = xЕщеЯчейки (x — 28, 3) .Interior.ColorIndex = xЯчейки (x — 28, 4) = xКонец, еслиДалее xКонец подписки

Примеры VBA ColorIndex

Установить цвет фона ячейки

1 Диапазон («A1»). Interior.ColorIndex = 6

Установить цвет шрифта ячейки

1 Диапазон («A1»). Font.ColorIndex = 5

Установить цвет границ ячеек

1 Диапазон («A1»). Borders.ColorIndex = 5

Получить индекс цвета фона ячейки

123 Dim col как целое числоcol = Range («A1»). Interior.ColorIndex

Установите цвет фона ячейки на цвет другой ячейки

1 Диапазон («A1»). Interior.ColorIndex = Range («B1»). Interior.ColorIndex

Свойство цвета VBA

Вместо использования свойства ColorIndex Excel / VBA вы можете использовать свойство Color. Свойство Color принимает два типа ввода:

  1. vbColor
  2. Цвета RGB

Мы обсудим это ниже:

Цвет VB

VB Color — самый простой способ установить цвета в VBA. Однако он также наименее гибкий. Чтобы установить цветовой код с помощью vbColor, используйте таблицу ниже:

Однако, как видно из таблицы, ваши возможности крайне ограничены.

Установить цвет фона ячейки

1 Диапазон («A1»). Interior.Color = vbYellow

Установить цвет шрифта ячейки

1 Диапазон («A1»). Font.Color = vbBlue

Установить цвет границ ячеек

1 Диапазон («A1»). Borders.Color = vbRed

Установите цвет фона ячейки на цвет другой ячейки

1 Диапазон («A1»). Interior.Color = Range («B1»). Interior.Color

Цвета RGB

RGB означает красный зеленый синий. Это три основных цвета, которые можно комбинировать для получения любого другого цвета. При вводе цветов как RGB введите значение от 0 до 255 для каждого цветового кода.

Вот пример:

1 Диапазон («A1»). Interior.Color = RGB (255,255,0)

Выше мы установили красный = 255 (максимальное значение), зеленый = 255 (максимальное значение) и синий = 0 (минимальное значение). Это устанавливает желтый цвет фона ячейки.

Вместо этого мы можем установить цвет шрифта ячейки на фиолетовый:

1 Диапазон («A1»). Interior.Color = RGB (128,0,128)

Существует множество онлайн-инструментов для поиска кода RGB для желаемого цвета (вот один).

Список кодов ColorIndex и цвета RGB в Access VBA

Access использует формы для отображения данных. Коды ColorIndex можно использовать для программного изменения цвета фона и цвета переднего плана объектов в формах Access.

12345 Частная подпрограмма cmdSave_Click ()’изменить цвет фона кнопки сохранения при сохранении записи.DoCmd.RunCommand acCmdSaveRecordcmdSave.BackColor = vbGreenКонец подписки

Вы поможете развитию сайта, поделившись страницей с друзьями

Like this post? Please share to your friends:
  • Vba excel таблица данных в массив
  • Vba excel считать текст
  • Vba excel считать значения с ячеек
  • Vba excel счетчик цикла
  • Vba excel счетчик строк