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.
Содержание
- Chr function
- Syntax
- Remarks
- Example
- See also
- Support and feedback
- Asc function
- Syntax
- Remarks
- Example
- See also
- Support and feedback
- Функция Asc
- Синтаксис
- Замечания
- Пример
- См. также
- Поддержка и обратная связь
- Character set (128 — 255)
- See also
- Support and feedback
Chr function
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.
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.
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.
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.
See also
Support and feedback
Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.
Источник
Asc function
Returns an Integer representing the character code corresponding to the first letter in a string.
Syntax
Asc(string)
The required string argument is any valid string expression. If the string contains no characters, a run-time error occurs.
The range for returns is 0–255 on non-DBCS systems, but -32768–32767 on DBCS systems.
The AscB function is used with byte data contained in a string. Instead of returning the character code for the first character, AscB returns the first byte. The AscW function returns the Unicode character code except on platforms where Unicode is not supported, in which case, the behavior is identical to the Asc function.
Visual Basic for the Macintosh does not support Unicode strings. Therefore, AscW (n) cannot return all Unicode characters for n values in the range of 128–65,535, as it does in the Windows environment. Instead, AscW (n) attempts a «best guess» for Unicode values n greater than 127. Therefore, you should not use AscW in the Macintosh environment.
The functions Chr(), ChrB(), and ChrW() are the opposite of Asc(), AscB(), and AscW(). The Chr() functions convert an integer to a character string.
Example
This example uses the Asc function to return a character code corresponding to the first letter in the string.
See also
Support and feedback
Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.
Источник
Функция Asc
Возвращает целое значение, представляющее код символа, который соответствуют первому символу строки.
Синтаксис
Asc(string)
Обязательный строковыйаргумент — это любое допустимое строковое выражение. Если string не содержит символов, возникает ошибка выполнения.
Замечания
Диапазон возвращаемых значений составляет 0–255 в системах, отличных от DBCS, и от -32768 до 32767 в системах DBCS .
Функция AscB используется для работы с байтами, содержащимися в строке. Вместо кода первого символа AscB возвращает первый байт. Функция AscW возвращает код символов в кодировке Unicode, за исключением платформ, в которых Unicode не поддерживается — в этом случае поведение функции аналогично функции Asc.
Visual Basic для macOS не поддерживает строки Юникода. Таким образом, AscW (n) не может возвращать все символы Юникода для n значений в диапазоне от 128 до 65 535, как это делается в среде Windows. Вместо этого AscW (n) пытается создать «лучшее предположение» для значений Юникода n больше 127. Поэтому не используйте функцию AscW в среде Macintosh.
Функции Chr(), ChrB() и ChrW() противоположны Asc(), AscB() и AscW(). Функции Chr() преобразуют целое число в символьную строку.
Пример
В примере функция Asc возвращает код символа, соответствующий первому символу строки.
См. также
Поддержка и обратная связь
Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.
Источник
Character set (128 — 255)
—>
Code | Character | Code | Character | Code | Character | Code | Character |
---|---|---|---|---|---|---|---|
128 | € | 160 | [space] | 192 | À | 224 | à |
129 | 161 | ВЎ | 193 | ГЃ | 225 | ГЎ | |
130 | ‚ | 162 | ¢ | 194 | Â | 226 | â |
131 | Ж’ | 163 | ВЈ | 195 | Гѓ | 227 | ГЈ |
132 | „ | 164 | ¤ | 196 | Ä | 228 | ä |
133 | … | 165 | ¥ | 197 | Å | 229 | å |
134 | †| 166 | ¦ | 198 | Æ | 230 | æ |
135 | ‡ | 167 | § | 199 | Ç | 231 | ç |
136 | Л† | 168 | ВЁ | 200 | Г€ | 232 | ГЁ |
137 | ‰ | 169 | © | 201 | É | 233 | é |
138 | Е | 170 | ВЄ | 202 | ГЉ | 234 | ГЄ |
139 | ‹ | 171 | « | 203 | Ë | 235 | ë |
140 | Е’ | 172 | В¬ | 204 | ГЊ | 236 | Г¬ |
141 | 173 | В | 205 | ГЌ | 237 | Г | |
142 | ЕЅ | 174 | В® | 206 | ГЋ | 238 | Г® |
143 | 175 | ВЇ | 207 | ГЏ | 239 | ГЇ | |
144 | 176 | В° | 208 | Гђ | 240 | Г° | |
145 | †| 177 | ± | 209 | Ñ | 241 | ñ |
146 | ’ | 178 | ² | 210 | Ò | 242 | ò |
147 | “ | 179 | ³ | 211 | Ó | 243 | ó |
148 | ” | 180 | ´ | 212 | Ô | 244 | ô |
149 | • | 181 | µ | 213 | Õ | 245 | õ |
150 | – | 182 | ¶ | 214 | Ö | 246 | ö |
151 | — | 183 | · | 215 | × | 247 | ÷ |
152 | Лњ | 184 | Вё | 216 | Г | 248 | Гё |
153 | в„ў | 185 | В№ | 217 | Г™ | 249 | Г№ |
154 | ЕЎ | 186 | Вє | 218 | Гљ | 250 | Гє |
155 | › | 187 | » | 219 | Û | 251 | û |
156 | Е“ | 188 | Вј | 220 | Гњ | 252 | Гј |
157 | 189 | ВЅ | 221 | Гќ | 253 | ГЅ | |
158 | Еѕ | 190 | Вѕ | 222 | Гћ | 254 | Гѕ |
159 | Её | 191 | Вї | 223 | Гџ | 255 | Гї |
Character 160 is a no-break space. Character 173 is a soft hyphen. Some characters aren’t supported by Microsoft Windows (characters 129, 141, 143, 144, and 157).
The values in the table are the Windows default. However, values in the ANSI character set above 127 are determined by the code page specific to your operating system.
See also
Support and feedback
Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.
Источник
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]
Работа с текстом в коде 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):
Код имитации печатной машинки состоит из двух процедур, первая из которых замедляет выполнение второй, создавая паузу перед отображением очередного символа, что и создает эффект печатающей машинки:
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 запустит замедленную печать символов в поле надписи, имитируя печатную машинку.
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 | Char | 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
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