Excel vba chr коды

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

Функции для работы с текстом

Основные функции для работы с текстом в VBA Excel:

Функция Описание
Asc(строка) Возвращает числовой код символа, соответствующий первому символу строки. Например: MsgBox Asc(«/Stop»). Ответ: 47, что соответствует символу «/».
Chr(код символа) Возвращает строковый символ по указанному коду. Например: MsgBox Chr(47). Ответ: «/».
Format(Expression, [FormatExpression], [FirstDayOfWeek], [FirstWeekOfYear]) Преобразует число, дату, время в строку (тип данных Variant (String)), отформатированную в соответствии с инструкциями, включенными в выражение формата. Подробнее…
InStr([начало], строка1, строка2, [сравнение]) Возвращает порядковый номер символа, соответствующий первому вхождению одной строки (строка2) в другую (строка1) с начала строки. Подробнее…
InstrRev(строка1, строка2, [начало, [сравнение]]) Возвращает порядковый номер символа, соответствующий первому вхождению одной строки (строка2) в другую (строка1) с конца строки. Подробнее…
Join(SourceArray,[Delimiter]) Возвращает строку, созданную путем объединения нескольких подстрок из массива. Подробнее…
LCase(строка) Преобразует буквенные символы строки в нижний регистр.
Left(строка, длина) Возвращает левую часть строки с заданным количеством символов. Подробнее…
Len(строка) Возвращает число символов, содержащихся в строке.
LTrim(строка) Возвращает строку без начальных пробелов (слева). Подробнее…
Mid(строка, начало, [длина]) Возвращает часть строки с заданным количеством символов, начиная с указанного символа (по номеру). Подробнее…
Replace(expression, find, replace, [start], [count], [compare]) Возвращает строку, полученную в результате замены одной подстроки в исходном строковом выражении другой подстрокой указанное количество раз. Подробнее…
Right(строка, длина) Возвращает правую часть строки с заданным количеством символов. Подробнее…
RTrim(строка) Возвращает строку без конечных пробелов (справа). Подробнее…
Space(число) Возвращает строку, состоящую из указанного числа пробелов. Подробнее…
Split(Expression,[Delimiter],[Limit],[Compare]) Возвращает одномерный массив подстрок, извлеченных из указанной строки с разделителями. Подробнее…
StrComp(строка1, строка2, [сравнение]) Возвращает числовое значение Variant (Integer), показывающее результат сравнения двух строк. Подробнее…
StrConv(string, conversion) Изменяет регистр символов исходной строки в соответствии с заданным параметром «conversion». Подробнее…
String(число, символ) Возвращает строку, состоящую из указанного числа символов. В выражении «символ» может быть указан кодом символа или строкой, первый символ которой будет использован в качестве параметра «символ». Подробнее…
StrReverse(строка) Возвращает строку с обратным порядком следования знаков по сравнению с исходной строкой. Подробнее…
Trim(строка) Возвращает строку без начальных (слева) и конечных (справа) пробелов. Подробнее…
UCase(строка) Преобразует буквенные символы строки в верхний регистр.
Val(строка) Возвращает символы, распознанные как цифры с начала строки и до первого нецифрового символа, в виде числового значения соответствующего типа. Подробнее…
WorksheetFunction.Trim(строка) Функция рабочего листа, которая удаляет все лишние пробелы (начальные, конечные и внутренние), оставляя внутри строки одиночные пробелы.

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

Ключевые слова для работы с текстом

Ключевое слово Описание
& Оператор & объединяет два выражения (результат = выражение1 & выражение2). Если выражение не является строкой, оно преобразуется в Variant (String), и результат возвращает значение Variant (String). Если оба выражения возвращают строку, результат возвращает значение String.
vbCrLf Константа vbCrLf сочетает в себе возврат каретки и перевод строки (Chr(13) + Chr(10)) и переносит последующий текст на новую строку (результат = строка1 & vbCrLf & строка2).
vbNewLine Константа vbNewLine в VBA Excel аналогична константе vbCrLf, также сочетает в себе возврат каретки и перевод строки (Chr(13) + Chr(10)) и переносит текст на новую строку (результат = строка1 & vbNewLine & строка2).

Примеры

Вывод прямых парных кавычек

Прямые парные кавычки в VBA Excel являются спецсимволами и вывести их, заключив в самих себя или в одинарные кавычки (апострофы), невозможно. Для этого подойдет функция Chr:

Sub Primer1()

    ‘Вывод одной прямой парной кавычки

MsgBox Chr(34)

    ‘Отображение текста в прямых кавычках

MsgBox Chr(34) & «Волга» & Chr(34)

    ‘Вывод 10 прямых парных кавычек подряд

MsgBox String(10, Chr(34))

End Sub

Смотрите интересное решение по выводу прямых кавычек с помощью прямых кавычек в первом комментарии.

Отображение слов наоборот

Преобразование слова «налим» в «Милан»:

Sub Primer2()

Dim stroka

    stroka = «налим»

    stroka = StrReverse(stroka) ‘милан

    stroka = StrConv(stroka, 3) ‘Милан

MsgBox stroka

End Sub

или одной строкой:

Sub Primer3()

MsgBox StrConv(StrReverse(«налим»), 3)

End Sub

Преобразование слова «лето» в «отель»:

Sub Primer4()

Dim stroka

    stroka = «лето»

    stroka = StrReverse(stroka) ‘отел

    stroka = stroka & «ь» ‘отель

MsgBox stroka

End Sub

или одной строкой:

Sub Primer5()

MsgBox StrReverse(«лето») & «ь»

End Sub

Печатная машинка

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

Для реализации этого примера понадобится пользовательская форма (UserForm1) с надписью (Label1) и кнопкой (CommandButton1):

Пользовательская форма с элементами управления Label и CommandButton

Код имитации печатной машинки состоит из двух процедур, первая из которых замедляет выполнение второй, создавая паузу перед отображением очередного символа, что и создает эффект печатающей машинки:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

Sub StopSub(Pause As Single)

Dim Start As Single

Start = Timer

    Do While Timer < Start + Pause

       DoEvents

    Loop

End Sub

Private Sub CommandButton1_Click()

Dim stroka As String, i As Byte

stroka = «Печатная машинка!»

Label1.Caption = «»

    For i = 1 To Len(stroka)

        Call StopSub(0.25) ‘пауза в секундах

        ‘следующая строка кода добавляет очередную букву

        Label1.Caption = Label1.Caption & Mid(stroka, i, 1)

    Next

End Sub

Обе процедуры размещаются в модуле формы. Нажатие кнопки CommandButton1 запустит замедленную печать символов в поле надписи, имитируя печатную машинку.


title keywords f1_keywords ms.prod ms.assetid ms.date ms.localizationpriority

Chr function (Visual Basic for Applications)

vblr6.chm1020927

vblr6.chm1020927

office

a9dc96ec-4719-8d24-144b-61d45fa58fe5

12/11/2019

high

Returns a String containing the character associated with the specified character code.

Syntax

Chr(charcode)
ChrB(charcode)
ChrW(charcode)

The required charcode argument is a Long that identifies a character.

Remarks

Numbers from 0–31 are the same as standard, nonprintable ASCII codes. For example, Chr(10) returns a linefeed character. The normal range for charcode is 0–255. However, on DBCS systems, the actual range for charcode is -32768–65535.

[!NOTE]
The ChrB function is used with byte data contained in a String. Instead of returning a character, which may be one or two bytes, ChrB always returns a single byte.

The ChrW function returns a String containing the Unicode character except on platforms where Unicode is not supported, in which case, the behavior is identical to the Chr function.

[!NOTE]
Visual Basic for the Macintosh does not support Unicode strings. Therefore, ChrW(n) cannot return all Unicode characters for n values in the range of 128–65,535, as it does in the Windows environment. Instead, ChrW(n) attempts a «best guess» for Unicode values n greater than 127. Therefore, you should not use ChrW in the Macintosh environment.

The functions Asc(), AscB(), and AscW() are the opposite of Chr(), ChrB(), and ChrW(). The Asc() functions convert a string to an integer.

Example

This example uses the Chr function to return the character associated with the specified character code.

Dim MyChar
MyChar = Chr(65)    ' Returns A.
MyChar = Chr(97)    ' Returns a.
MyChar = Chr(62)    ' Returns >.
MyChar = Chr(37)    ' Returns %.

See also

  • Character set (0 — 127)
  • Character set (128 — 255)
  • Functions (Visual Basic for Applications)
  • Asc(), AscB(), and AscW() functions

[!includeSupport and feedback]

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 Access Excel VBA tutorial explains how to use Chr Function to convert ASCII value to character, and convert from character to ASCII value with ASC Function

What is Access Excel VBA Chr Function?

Access Excel VBA Chr Function converts ASCII value to a character. 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.

Chr Function is applicable to: Excel VBA, Access, Access VBA

Refer to the below table, Excel Char Function will convert the “Dec” value to “Char” 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 Access Excel  VBAChr Function?

1. To import special characters. However, Windows may not be able to show those characters.

2. Start a new line in a Cell with Char(10) in worksheet (must need to set Wrap Text first) and MsgBox message

Syntax of Access Excel VBA Chr Function

CHR( ascii_value )

ascii_value is the ASCII value used to retrieve the character.

Note that Chr Function also exists for worksheet but the name is Char. You can convert the character back into ASCII value using Code Function in worksheet / ASC Function in VBA

Example of Access Excel VBA Chr Function

Formula Result Explanation
Chr(65) A
Chr(90) Z
Range(“A1”).Value = “line one” & Chr(10) & “line two” line one
line two
Start a new line with Char(10)
 Range(“A1”).Value = Replace(“line one,line two”, “,”, Chr(10)) line one
line two
 Replace comma with new line

To start a new line in VBA MsgBox

msgbox_03

Public Sub test1()
    sInput = MsgBox("Are you sure to delete the data?" & Chr(10) & "Data will be deleted permanently")
End Sub

Outbound References

http://www.techonthenet.com/excel/formulas/char.php

Excel VBA CHR

VBA CHR Function

VBA CHR function is categorized under Text/String function.

Each & every character in Excel has a specific assigned number code (ASCII code) to itself. VBA Chr function returns or results in String containing the character associated with the specified character code (also referred to as ASCII value). ASCII stands for American Standard Code for Information Interchange

ASCII_Value: It is a standard for the relationship between a number of value and a character type.

ASCII value should be in the range of or between 0 and 255 which are categorized into 3 types.

  • Between 0 to 31 range is an ASCII control character OR Non-Printing Control Codes.
  • 32 to 127 range is an ASCII printable characters.
  • 128 to 255 range is an Extended ASCII codes.

Syntax of CHR in Excel VBA

After typing Chr, click on spacebar the below-mentioned syntax appears.

Syntax VBA CHR

Chr( ascii_value ) or Chr(charcode)

It contains one input parameter or argument (Compulsory & required), Charcode argument is a Long which identifies a character. It will result in both printable and unprintable characters.

Mapping of Characters with their ASCII Values (Each code explained in Excel file _ CHARACTER CODE DESCRIPTION SHEET)

1 – 9 58 : 87 W 116 t 145 174 ® 203 Ë 232 è
10 59 ; 88 X 117 u 146 175 ¯ 204 Ì 233 é
11 – 31 60 < 89 Y 118 v 147 176 ° 205 Í 234 ê
32 61 = 90 Z 119 w 148 177 ± 206 Î 235 ë
33 ! 62 > 91 [ 120 x 149 178 ² 207 Ï 236 ì
34 63 ? 92 121 y 150 179 ³ 208 Ð 237 í
35 # 64 @ 93 ] 122 z 151 180 ´ 209 Ñ 238 î
36 $ 65 A 94 ^ 123 { 152 ˜ 181 µ 210 Ò 239 ï
37 % 66 B 95 _ 124 | 153 182 211 Ó 240 ð
38 & 67 C 96 ` 125 } 154 š 183 · 212 Ô 241 ñ
39 68 D 97 a 126 ~ 155 184 ¸ 213 Õ 242 ò
40 ( 69 E 98 b 127  156 œ 185 ¹ 214 Ö 243 ó
41 ) 70 F 99 c 128 157  186 º 215 × 244 ô
42 * 71 G 100 d 129  158 ž 187 » 216 Ø 245 õ
43 + 72 H 101 e 130 159 Ÿ 188 ¼ 217 Ù 246 ö
44 , 73 I 102 f 131 ƒ 160 189 ½ 218 Ú 247 ÷
45 74 J 103 g 132 161 ¡ 190 ¾ 219 Û 248 ø
46 . 75 K 104 h 133 162 ¢ 191 ¿ 220 Ü 249 ù
47 / 76 L 105 i 134 163 £ 192 À 221 Ý 250 ú
48 0 77 M 106 j 135 164 ¤ 193 Á 222 Þ 251 û
49 1 78 N 107 k 136 ˆ 165 ¥ 194 Â 223 ß 252 ü
50 2 79 O 108 l 137 166 ¦ 195 Ã 224 à 253 ý
51 3 80 P 109 m 138 Š 167 § 196 Ä 225 á 254 þ
52 4 81 Q 110 n 139 168 ¨ 197 Å 226 â 255 ÿ
53 5 82 R 111 o 140 Œ 169 © 198 Æ 227 ã
54 6 83 S 112 p 141  170 ª 199 Ç 228 ä
55 7 84 T 113 q 142 Ž 171 « 200 È 229 å
56 8 85 U 114 r 143  172 ¬ 201 É 230 æ
57 9 86 V 115 s 144  173 202 Ê 231 ç

How to Use CHR Function in Excel VBA?

Below are the different examples to use CHR Function in Excel using VBA code.

You can download this VBA CHR Excel Template here – VBA CHR Excel Template

Now let us test this CHR Function through some examples and learn how they work.

VBA CHR Function – Example #1

Step 1: Select or click on Visual Basic in the Code group on the Developer tab or you can directly click on Alt + F11 shortcut key.

VBA Char Example 1-1

Step 2: Now, you can see VB Editor window, under the project window, in VBA project, you can see work file listed (i.e. Sheet1 (VB_CHR)

VBA CHR Module Example 1.2

To create a blank module, under the Microsoft excel objects, right-click on sheet 1(VB_CHR) click on Insert and select Module so that a new blank module gets created.

VBA CHR Function – Example #2

Step 1: Now the blank module is created, it is also called a code window, where you can start writing VBA CHR function statement codes.

Code:

Sub CHRAC()

Sheet1.Range("D6") = CHR(77)

End Sub

 Example 2.1

Step 2: The above-mentioned VBA code returns or results in an Upper-case alphabet M in “D6” cell, i.e. for the ASCII value 77.

Example 1.2

VBA CHR Function – Example #3

Step 1: Start another subprocedure as follows,

Code:

Sub CHRAC1()

End Sub

Example 3.1

Step 2: Similarly, multiple character codes can be obtained in the cell with the help of below-mentioned code

Code:

Sub CHRAC1()

Sheet1.Range("D9") = CHR(37)
Sheet1.Range("D11") = CHR(47)
Sheet1.Range("D13") = CHR(57)
Sheet1.Range("D15") = CHR(128)

End Sub

VBA CHR Example 3.2

Step 3: Let us execute the above code. Once you run the above-mentioned code, you can notice a character code in the excel file.

VBA CHR Example 2.2

  • CHR(37) will return a % (Percent symbol) in a cell “D9” whereas,
  • CHR(47) returns / (Slash/Divide symbol) in the cell “D11”
  • CHR(57) returns a numeric value 9 in the cell  “D13” &
  • CHR(128) returns a Euro Sign in the cell “D11”

VBA CHR Function – Example #4

In the below-mentioned example, suppose I want to insert double quotation for the middle name i.e. MANI

Here, for this, I can use VBA CHR function.

Example 4.0

Step 1: Once, I run the below-mentioned code with the CHR code 34, it will insert a double quotation mark in the middle name.

Code:

Sub CHRAC2()

Sheet3.Range("C4") = "MANI" & CHR(34) & "RAM" & CHR(34) & "KUMAR"

End Sub

VBA CHR Example 4.1
Step 2: Let us execute the above code by clicking on the play button and the result in the below-mentioned output in the cell “E19”

VBA chr 2

VBA CHR Function – Example #5

In the below-mentioned example, suppose I want to add a trademark symbol for company i.e. GOOGLE

Here, for this, I can use VBA CHR function with ASCII code “153”

Example 5.1

Step 1: Once, I run the below-mentioned code with the CHR code 153, it will show TM symbol for the word GOOGLE.

Code:

Sub CHRAC3()

Sheet4.Range("C3") = "GOOGLE" & CHR(153)

End Sub

Example 5.2

Step 2: The above code, result in the below-mentioned output in the cell “K18”

VBA Chr3

Save your workbook as “Excel macro-enabled workbook”. By clicking on save as at the left corner of the worksheet. Once again if you open a file, you can click on shortcut key i.e. Fn + Alt +F8, “Macro” dialog box appears, where you can run a saved macro code of your choice or you can click on Fn + Alt + F11 for a full macro window.

Things to Remember

If you enter an invalid number to the Chr function i.e. Number in a range of lesser than 0 or more than 255, then you will get the error i.e. Run-time error.

Recommended Articles

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

  1. VBA Copy Paste
  2. VBA RGB
  3. VBA Subscript out of Range
  4. VBA XML

Понравилась статья? Поделить с друзьями:
  • Excel vba break for if
  • Excel vba checkbox на форме
  • Excel vba borders внешняя граница
  • Excel vba checkbox values
  • Excel vba borders range