Chr vba excel таблица

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

VBA CHR function in Excel is categorized as a Text/String function in VBA. It is a built-in function in MS Office Excel VBA. This function returns the character of the given ASCII value (or Character Code). The ASCII value should be between 0 and 255. ASCII stands for American Standard Code for Information Interchange. It has one input parameter. The CHR function can be used in only VBA. We can’t use this function as a worksheet function. This function can be used in either procedure or function in a VBA editor window in Excel. We can use this VBA CHR function any number of times in any number of procedures or functions. In the following section we learn what is the syntax and parameters of the CHR function, where we can use this VBA CHR function and real-time examples.

Table of Contents

  • Objective
  • Syntax of VBA CHR Function
  • Parameters or Arguments
  • Where we can apply or use VBA CHR Function?
  • Example 1: Display the ASCII character of ‘65’
  • Example 2: Display the ASCII character of ‘97’
  • Example 3: Display the ASCII character of ‘64‘
  • Example 4: Display the ASCII character of ‘270‘
  • ASCII Table Chart
  • Instructions to Run VBA Macro Code
  • Other Useful Resources

The syntax of the VBA CHR function is

Chr (CharCode)

The VBA Chr function returns a string for the given character code.

Parameters or Arguments

The CHR function has one input (integer) parameter or argument.
Where
CharCode: It is a required parameter. The ‘CharCode’ is the character code for which we want to display respective ASCII character.

Where we can apply or use VBA CHR Function?

We can use this VBA CHR function in MS Office 365, MS Excel 2016, MS Excel 2013, 2011, Excel 2010, Excel 2007, Excel 2003, Excel 2016 for Mac, Excel 2011 for Mac, Excel Online, Excel for iPhone, Excel for iPad, Excel for Android tablets and Excel for Android Mobiles.

Example 1: Display the ASCII character of ‘65’

Here is a simple example of the VBA CHR function. This below example macro takes ‘65’ as input and generates output of specified value ASCII character.

'Display the ASCII character of '65'
Sub VBA_CHR_Function_Ex1()

    Dim sOutput As String, iInput_Val As Integer
    
    iInput_Val = 65
    
    sOutput = Chr(iInput_Val)
    
    MsgBox "The ASCII character of '65' is :" & sOutput, vbInformation, "VBA CHR Function"

End Sub 

Output: Here is the screen shot of first example output.
VBA CHR Function

Example 2: Display the ASCII character of ’97’

Let us see another example of the VBA CHR function. This below example macro takes ‘97’ as input and generates output of specified value ASCII character.

'Display the ASCII character of '97'
Sub VBA_CHR_Function_Ex2()

    Dim sOutput As String, iInput_Val As Integer
    
    iInput_Val = 97
    
    sOutput = Chr(iInput_Val)
    
    MsgBox "The ASCII character of '97' is :" & sOutput, vbInformation, "VBA CHR Function"

End Sub 

Output: Here is the screen shot of second example output.
VBA CHR Function

Example 3: Display the ASCII character of ’64’

Here is a simple example of the VBA CHR function. This below example macro takes ‘64’ as input and generates output of specified value ASCII character.

'Display the ASCII character of '64'
Sub VBA_CHR_Function_Ex3()

    Dim sOutput As String, iInput_Val As Integer
    
    iInput_Val = 64
    
    sOutput = Chr(iInput_Val)
    
    MsgBox "The ASCII character of '64' is :" & sOutput, vbInformation, "VBA CHR Function"

End Sub 

Output: Here is the screen shot of third example output.
VBA CHR Function

Example 4: Display the ASCII character of ‘270’

Let us see another example of the VBA CHR function. This below example macro takes ‘270’ as input and generates an error. Because specified input could be between 0 and 255. Otherwise, it returns an error.
Error Description: Run Time Error – Invalid Procedure Call or Argument

'Display the ASCII character of '270'
Sub VBA_CHR_Function_Ex4()

    Dim sOutput As String, iInput_Val As Integer
    
    iInput_Val = 270
    
    sOutput = Chr(iInput_Val)
    
    MsgBox "The ASCII character of '270' is :" & sOutput, vbInformation, "VBA CHR Function"

End Sub

Output: Here is the screen shot of fourth example output.
VBA CHR Function

ASCII Table Chart

Please click on below link to see ASCII Table Chart.

ASCII Table Chart

Instructions to Run VBA Macro Code or Procedure:

You can refer the following link for the step by step instructions.

Instructions to run VBA Macro Code

Other Useful Resources:

Click on the following links of the useful resources. These helps to learn and gain more knowledge.

VBA Tutorial VBA Functions List VBA Arrays in Excel Blog

VBA Editor Keyboard Shortcut Keys List VBA Interview Questions & Answers

Excel VBA CHR Function

VBA CHR is a built-in function that falls under the String/Text Functions category used to get the character equivalent to the ASCII code. For example, the equivalent Excel Workspace function of CHR is Application.WorksheetFunction.CHAR.

Table of contents
  • Excel VBA CHR Function
    • Example
    • How to Create a Button in Excel?
    • Things to Remember
    • Recommended Articles

Given below is the Chr syntax.

vba chr syntax

This function has one argument. Where,

Charco de = This is a required parameter. It is the ASCII code for which an equivalent character is to be retrieved.

The function returns a string value denoting the character equivalent to the given ASCII code. ASCII is a subset of the Unicode character coding standard formed by 128 symbols in the character set, including uppercase, lowercase letters, numbers, special characters, control characters, and punctuation marks. In addition, every symbol in the character set has an equivalent Decimal value (0 to 127), a Hexadecimal value, and an Octal value.

vba-chr

Example

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

Step 1: In the Excel sheet, add two header texts in cells A1 and C1, as shown in the figure below. Column A to enter the ASCII code and column C to print the corresponding character calculated using the CHR function.

vba chr example 1.11

Step 2: Follow the steps in the next section to create a Button in the Excel workbook (please scroll the article) and change its caption to “Click here.”

vba chr example 1.12

Step 3: Write the following code snippet in VBA. The code reads the value from cell A2, which is given as an input to function CHR. The result is retrieved in String char1 and then assigned to cell C2.

Code:

Sub Button1_Click()
'This function returns the character for the value entered in cell A2
Dim char1 As String
'Declare char1 variable as String

char1 = Chr(Range("A2").Value)
'Read value from cell A2

Range("C2").Value = char1
'Print output in cell C2

End Sub

vba chr example 1.13

Step 4: Save the VBA Excel codeVBA code refers to a set of instructions written by the user in the Visual Basic Applications programming language on a Visual Basic Editor (VBE) to perform a specific task.read more and go back to the Excel workbook to enter the input value in cell A2, as shown below.

Enter 65 as an ASCII input for the corresponding character to be found in cell C2.

vba chr example 1.14

Step 5: Click the “Click here” button to print the result in cell C2.

vba chr example 1.15

Observe the result printed in cell C2. The code snippet we wrote in step 3 is responsible for reading the input from cell A2, running the Chr function on it, and printing the value in cell C2, as shown below.

VBA CHR GIF 1

Here, the input given is 65, and the output received is A. So, Chr (65) = A.

Step 6: Try changing the input in cell A2 and observe that you get the respective output in cell C2, as shown below.

E.g. CHR (37) = % and so on.

VBA CHR GIF 2

How to Create a Button in Excel?

As a VBA function, we can use it in excel macroA macro in excel is a series of instructions in the form of code that helps automate manual tasks, thereby saving time. Excel executes those instructions in a step-by-step manner on the given data. For example, it can be used to automate repetitive tasks such as summation, cell formatting, information copying, etc. thereby rapidly replacing repetitious operations with a few clicks.
read more
code, entered through the Microsoft Visual Basic Editor integrated into MS Excel. Refer to the steps given below to know more.

Step 1: Turn on Developer Mode in ExcelEnabling the developer tab in excel can help the user perform various functions for VBA, Macros and Add-ins like importing and exporting XML, designing forms, etc. This tab is disabled by default on excel; thus, the user needs to enable it first from the options menu.read more

For any VBA functionVBA functions serve the primary purpose to carry out specific calculations and to return a value. Therefore, in VBA, we use syntax to specify the parameters and data type while defining the function. Such functions are called user-defined functions.read more to use in Excel, one must turn on the Developer Mode from File->Options Menu, as shown in the figure below.

Click on File – > Excel Options – >Customize Ribbon ->Developer -> OK

vba chr example 1.1

As a result, a new toolbar option named “Developer” will be added to the workbook, as shown in the picture below.

vba chr example 1.2

Step 2: Saving the workbook

Save the Excel Workbook as an “Excel Macro-Enabled Workbook.”

vba chr example 1.3

Step 3: Insert a form control in a workbookExcel Form Controls are objects which can be inserted at any place in the worksheet to work with data and handle the data as specified. These controls are compatible with excel and can create a drop-down list in excel, list boxes, spinners, checkboxes, scroll bars.read more

  • Click on the “Developer” tab. And in the “Controls” sub-section, click on the “Insert” option in VBA.

example 1.4

  • Choose the first control, “Button (Form Control).”

vba chr example 1.5

  • Observe that the workbook cursor changes to a drawable icon.
  • As you try to draw a button, a new dialog window named ‘Assign Macro’ will launch. As we learn more, you can specify the macro name you will use in the VB code. E.g., Button1_Click. Click “OK.”

example 1.6

  • A button will then automatically get inserted into the workbook. The button caption text is editable, and we can edit it by double-clicking on the button.

vba chr example 1.7

Step 4: Write VB code

  • Select the button and click on the first option from the left under the “Code” sub-section of the “Developer” tab, i.e., “Visual Basic.”

example 1.8

  • It will launch a new window of the VBA project, as shown in the picture below.

example 1.9

  • As shown in the above figure, an empty skeleton for the earlier created macro, i.e., Button1_Click, is populated in the VB code window.
  • You can write the macro definition as per your intention. Here, we will see an example of the VBA CHAR function in the following section.

Step 5: Switching between Excel workbook and VB IDE

You can switch between the Excel workbook and the VB IDE by clicking on the extreme left icon below the “File” menu, i.e., “View Microsoft Excel,” as shown below.

example 1.10

Things to Remember

  • The CHR function can return printable and non-printable characters present on the keyboard and understood by the computer. E.g., letters, numbers, and other special characters are printable characters. However, other keys such as “Enter,” “Spacebar,” and “Esc” are non-printable characters.
  • The CHR is a VBA function and cannot be used in Excel as it is. Its corresponding function in Excel is Application.WorksheetFunction.CHAR.

Recommended Articles

This article has been a guide to VBA CHR. Here we discuss how to get a character of the ASCII code in Excel using the VBA CHR function along with examples and codes. You can learn more about VBA from the following articles: –

  • Switch Function in VBA
  • VBA Break For Loop
  • VBA InStr Examples

Работа с текстом в коде 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 запустит замедленную печать символов в поле надписи, имитируя печатную машинку.


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

Понравилась статья? Поделить с друзьями:
  • Chose the right word what where when
  • Chose the right word to complete these sentences
  • Chose the right word to complete the sentences i bought
  • Chose the right word is or are
  • Chose the right word home or house