Главная » Функции VBA »
28 Апрель 2011 351416 просмотров
- ASC()— эта функция позволяет вернуть числовой код для переданного символа. Например, ASC(
"D"
) вернет 68. Эту функцию удобно использовать для того, чтобы определить следующую или предыдущую букву. Обычно она используется вместе с функцией Chr(), которая производит обратную операцию — возвращает символ по переданному его числовому коду.Варианты этой функции — AscB() и AscW():- AscB() — возвращает только первый байт числового кода для символа.
- AscW() — возвращает код для символа в кодировке Unicode
- Chr() — возвращает символ по его числовому коду. Может использоваться в паре с функцией Asc(), но чаще всего её применяют, когда нужно вывести служебный символ (например кавычки —
"
), т.к. кавычки просто так в VBA-коде не ввести(нужно ставить двойные). Я обычно именно эту функцию и использую.Dim sWord As String sWord = Chr(34) & "Слово в кавычках" & Chr(34)
Есть варианты этой функции — ChrB() и ChrW(). Работают аналогично таким же вариантам для функции Asc().
- InStr() и InStrRev()— одна из самых популярных функций. Позволяет обнаружить в теле строковой переменной символ или последовательность символов и вернуть их позицию. Если последовательность не обнаружена, то возвращается 0.
Dim sStr As String sStr = "w" If InStr(1, "Hello, World!", sStr, vbTextCompare) > 0 Then MsgBox "Искомое слово присутствует!" Else MsgBox "Искомое слово отсутствует!" End If
Разница функций в том, что InStr() ищет указанное слово от начала строки, а InStrRev() с конца строки
- Left(), Right(), Mid()— возможность взять указанное вами количество символов из существующей строковой переменной слева, справа или из середины соответственно.
Dim sStr As String sStr = "Hello, World!" MsgBox Mid(sStr, 1, 5)
- Len() — возможность получить число символов в строке. Часто используется с циклами, операциями замены и т.п.
- LCase() и UCase() — перевести строку в нижний и верхний регистры соответственно. Часто используется для подготовки значения к сравнению, когда при сравнении регистр не важен (фамилии, названия фирм, городов и т.п.).
- LSet() и RSet() — возможность заполнить одну переменную символами другой без изменения ее длины (соответственно слева и справа). Лишние символы обрезаются, на место недостающих подставляются пробелы.
- LTrim(), RTrim(), Trim() — возможность убрать пробелы соответственно слева, справа или и слева, и справа.
- Replace()— возможность заменить в строке одну последовательность символов на другую.
Dim sStr As String sStr = "Hello, World!" MsgBox Replace(sStr, "Hello", "Bay")
- Space() — получить строку из указанного вами количества пробелов;
Еще одна похожая функция — Spc(), которая используется для форматирования вывода на консоль. Она размножает пробелы с учетом ширины командной строки. - StrComp() — возможность сравнить две строки.
- StrConv() — возможность преобразовать строку (в Unicode и обратно, в верхний и нижний регистр, сделать первую букву слов заглавной и т.п.):
Dim sStr As String sStr = "Hello, World!" MsgBox StrConv("Hello, World!", vbUpperCase)
В качестве второго параметра параметра могут применяться константы:
- vbUpperCase: Преобразует все текстовые символы в ВЕРХНИЙ РЕГИСТР
- vbLowerCase: Преобразует все текстовые символы в нижний регистр
- vbProperCase: Переводит первый символ каждого слова в Верхний Регистр
- *vbWide: Преобразует символы строки из однобайтовых в двухбайтовые
- *vbNarrow: Преобразует символы строки из двухбайтовых в однобайтовые
- **vbKatakana: Преобразует символы Hiragana в символы Katakana
- **vbHiragana: Преобразует символы Katakana в символы Hiragana
- ***vbUnicode: Преобразует строку в Юникод с помощью кодовой страницы системы по умолчанию
- ***vbFromUnicode: Преобразует строку из Юникод в кодовую страницу системы по умолчанию
* применимо для локализацией Дальнего востока
** применимо только для Японии
*** не поддерживается операционными системами под управлением Macintosh - StrReverse() — «перевернуть» строку, разместив ее символы в обратном порядке. Функция работает только начиная от Excel 2000 и выше. Пример использования функции, а так же иные методы переворачивания слова можно посмотреть в этой статье: Как перевернуть слово?
- Tab() — еще одна функция, которая используется для форматирования вывода на консоль. Размножает символы табуляции в том количестве, в котором вы укажете. Если никакое количество не указано, просто вставляет символ табуляции. Для вставки символа табуляции в строковое значение можно также использовать константу vbTab.
- String() — позволяет получить строку из указанного количества символов (которые опять-таки указываются Вами). Обычно используются для форматирования вывода совместно с функцией Len().
Статья помогла? Сделай твит, поделись ссылкой с друзьями!
Excel VBA ASC
ASCII which is American Standard Code for Information Interchange has introduced a proper structure for each number and alphabets. And these ASC Codes are frequently used in many programming languages. In VBA also, we have these ASC Codes applicable in many ways. These codes are created for each programming languages so that computer can understand which is being fed to it. ASCII is the numerical representation of every word and alphabet.
In ASC, we have different types of characters printing characters (which can be seen) to non-printing characters (which cannot be seen such as any process or spaces). For example, we someone says “Good Morning” to you then it is being communicated with sound waves. Now if same we want to feed this into a computer or send a message to anyone then the computer will convert the text “Good Morning” into ASC Codes and then the message will get transferred to that person. But again that person will receive the message in a text, not in some codes.
Formula For ASC Function in Excel VBA
Let us look below the formula for ASC function in VBA.
How to Use the ASC Function in Excel VBA?
Below are the different examples to use ASC function in Excel using VBA code.
You can download this VBA ASC Excel Template here – VBA ASC Excel Template
Excel VBA ASC – Example #1
We can get the table of ASC from the ASCII website. We have already shown that table for reference. Below is the table which has Dec, Hex, HTML ASC codes for special non-printing characters and alphabets from A to Z.
And moreover, we have ASC codes for special characters and some mathematical signs as well as shown below starting from 128 to 255.
In total, we have 255 ASC codes which can be used in VBA. Now we will implement these codes in VBA also.
- Go to VBA Insert menu option and open a Module as shown below.
- Now in the opened module write the subcategory of VBA ASC function as shown below.
Code:
Sub VBA_ASC() End Sub
- After that define a variable DIM with any name, let’s say it is “A” and assign it Integers. Although we will be giving text and numbers as an input to variable A but using Integer because VBA ASC function considers integers as an output in which input will be as a string. We will see this further.
Code:
Sub VBA_ASC() Dim A As Integer End Sub
- Now assign variable A to ASC function as shown below.
- Now select any word or alphabet as per need inside the brackets as shown below.
Code:
Sub VBA_ASC() Dim A As Integer A = Asc("B") End Sub
- Now to see the ASC code value it is best to use the message box. Assign a MsgBox to variable A as shown below.
Code:
Sub VBA_ASC() Dim A As Integer A = Asc("B") MsgBox A End Sub
- Once done, then click on the play button which is located below the menu bar to run the code.
We will see, the ASC code of alphabet “B” is coming as 66. This is the same code mentioned in ACS Table which we have been at the starting of example-1.
Excel VBA ASC – Example #2
In this example, we will see, how a complete word will be encoded with the help of VBA ASC. For this we will use the same code structure which we have seen in example-1, only keeping only brackets of ASC function blank as shown below.
Now let’s insert any word into those brackets. Let’s consider that word “Excel”
Code:
Sub VBA_ASC1() Dim A As Integer A = Asc("Excel") MsgBox A End Sub
Now compile the code and run it after that. We will see ASC function has generated the ASC code as 69 as shown below.
And if we match this ASC Code with the list which we saw in example-1, then we will see that for capital E which is at the start of Excel is marked as 69.
Excel VBA ASC – Example #3
In this example, we will see how a lower case letter of the same word can give ASC code. For this we will consider the same word which we have seen above example “Excel” but we will keep “e” in lower case. Consider the same body of code which we have used above.
Now in that bracket write “excel” in lower case.
Code:
Sub VBA_ASC2() Dim A As Integer A = Asc("excel") MsgBox A End Sub
Again, compile and run the code. We will see, for lower case “e” the ASC Code is coming as 101 as shown below.
If we match this with the list shown in example-1, we will see, for each lower case alphabet, there is separate ASC code given which is different than that of Upper case letters.
Excel VBA ASC – Example #4
In this example, we will see how a special character can be used to get the ASC code out of it. Again, we will continue using the same code format that we have seen in example-1.
Now insert any special character which is allowed to be used in VBA coding. We mostly use an ampersand (&) in VBA in different forms. So we will continue with the same here as well.
Code:
Sub VBA_ASC3() Dim A As Integer A = Asc("&") MsgBox A End Sub
Again compile the code and run. We will see the message box containing ASC Code as 38 as shown below.
And if we match this code with the table shown in example-1 we will see, for the ampersand (&) ASC code is defined as 38.
Pros of Excel VBA ASC
- ASC Code is very revolutionary when it got introduced, as it is very helpful in standardizing the transmission of computer codes and messages.
- For each letter respective of upper and lower cases, ASCII has given separate ASC code so that word in upper case and lower case will get encode as it is fed.
Things to Remember
- VBA doesn’t consider ASC codes of complex mathematical symbols which are the Extended ASCII Codes. An only simple character can be used to get it Dec ASC Code.
- Upper and lower case alphabets have different ASC codes.
- VBA generates only Dec of ASC codes.
- Once done, must save the file in Macro enabled excel format. So that VBA code can be retained.
Recommended Articles
This is a guide to VBA ASC Function. Here we discuss how to use ASC function in Excel VBA along with practical examples and a downloadable excel template. You can also go through our other suggested articles –
- VBA Match
- VBA StrComp
- VBA Web Scraping
- VBA XML
This page explains how to use Excel VBA ASCFunction to get ASCII value of a text, and how to check if a text contains an alphabet, number or symbol
Excel VBA ASC Function returns the ASCII value of the first character in a text. ASCII (American Standard Code for Information Interchange) uses 8-bit code units, an old encoding system which stores mainly numbers, lowercase letters a to z, uppercase letters A to Z, basic punctuation symbols, control codes. Many old systems still use this encoding system. 8 bit means the computer memory uses “8” digits with 1 and 0 combination (binary) to represent a character, 8 bits memory is equal to 1 byte.
Refer to the below table, Excel ASC Function will convert the “Char” value to “Dec” value.
Dec | Hex | Oct | Char | Description |
---|---|---|---|---|
0 | 0 | 000 | null | |
1 | 1 | 001 | start of heading | |
2 | 2 | 002 | start of text | |
3 | 3 | 003 | end of text | |
4 | 4 | 004 | end of transmission | |
5 | 5 | 005 | enquiry | |
6 | 6 | 006 | acknowledge | |
7 | 7 | 007 | bell | |
8 | 8 | 010 | backspace | |
9 | 9 | 011 | horizontal tab | |
10 | A | 012 | new line | |
11 | B | 013 | vertical tab | |
12 | C | 014 | new page | |
13 | D | 015 | carriage return | |
14 | E | 016 | shift out | |
15 | F | 017 | shift in | |
16 | 10 | 020 | data link escape | |
17 | 11 | 021 | device control 1 | |
18 | 12 | 022 | device control 2 | |
19 | 13 | 023 | device control 3 | |
20 | 14 | 024 | device control 4 | |
21 | 15 | 025 | negative acknowledge | |
22 | 16 | 026 | synchronous idle | |
23 | 17 | 027 | end of trans. block | |
24 | 18 | 030 | cancel | |
25 | 19 | 031 | end of medium | |
26 | 1A | 032 | substitute | |
27 | 1B | 033 | escape | |
28 | 1C | 034 | file separator | |
29 | 1D | 035 | group separator | |
30 | 1E | 036 | record separator | |
31 | 1F | 037 | unit separator | |
32 | 20 | 040 | space | |
33 | 21 | 041 | ! | |
34 | 22 | 042 | “ | |
35 | 23 | 043 | # | |
36 | 24 | 044 | $ | |
37 | 25 | 045 | % | |
38 | 26 | 046 | & | |
39 | 27 | 047 | ‘ | |
40 | 28 | 050 | ( | |
41 | 29 | 051 | ) | |
42 | 2A | 052 | * | |
43 | 2B | 053 | + | |
44 | 2C | 054 | , | |
45 | 2D | 055 | – | |
46 | 2E | 056 | . | |
47 | 2F | 057 | / | |
48 | 30 | 060 | 0 | |
49 | 31 | 061 | 1 | |
50 | 32 | 062 | 2 | |
51 | 33 | 063 | 3 | |
52 | 34 | 064 | 4 | |
53 | 35 | 065 | 5 | |
54 | 36 | 066 | 6 | |
55 | 37 | 067 | 7 | |
56 | 38 | 070 | 8 | |
57 | 39 | 071 | 9 | |
58 | 3A | 072 | : | |
59 | 3B | 073 | ; | |
60 | 3C | 074 | < | |
61 | 3D | 075 | = | |
62 | 3E | 076 | > | |
63 | 3F | 077 | ? | |
64 | 40 | 100 | @ | |
65 | 41 | 101 | A | |
66 | 42 | 102 | B | |
67 | 43 | 103 | C | |
68 | 44 | 104 | D | |
69 | 45 | 105 | E | |
70 | 46 | 106 | F | |
71 | 47 | 107 | G | |
72 | 48 | 110 | H | |
73 | 49 | 111 | I | |
74 | 4A | 112 | J | |
75 | 4B | 113 | K | |
76 | 4C | 114 | L | |
77 | 4D | 115 | M | |
78 | 4E | 116 | N | |
79 | 4F | 117 | O | |
80 | 50 | 120 | P | |
81 | 51 | 121 | Q | |
82 | 52 | 122 | R | |
83 | 53 | 123 | S | |
84 | 54 | 124 | T | |
85 | 55 | 125 | U | |
86 | 56 | 126 | V | |
87 | 57 | 127 | W | |
88 | 58 | 130 | X | |
89 | 59 | 131 | Y | |
90 | 5A | 132 | Z | |
91 | 5B | 133 | [ | |
92 | 5C | 134 | ||
93 | 5D | 135 | ] | |
94 | 5E | 136 | ^ | |
95 | 5F | 137 | _ | |
96 | 60 | 140 | ` | |
97 | 61 | 141 | a | |
98 | 62 | 142 | b | |
99 | 63 | 143 | c | |
100 | 64 | 144 | d | |
101 | 65 | 145 | e | |
102 | 66 | 146 | f | |
103 | 67 | 147 | g | |
104 | 68 | 150 | h | |
105 | 69 | 151 | i | |
106 | 6A | 152 | j | |
107 | 6B | 153 | k | |
108 | 6C | 154 | l | |
109 | 6D | 155 | m | |
110 | 6E | 156 | n | |
111 | 6F | 157 | o | |
112 | 70 | 160 | p | |
113 | 71 | 161 | q | |
114 | 72 | 162 | r | |
115 | 73 | 163 | s | |
116 | 74 | 164 | t | |
117 | 75 | 165 | u | |
118 | 76 | 166 | v | |
119 | 77 | 167 | w | |
120 | 78 | 170 | x | |
121 | 79 | 171 | y | |
122 | 7A | 172 | z | |
123 | 7B | 173 | { | |
124 | 7C | 174 | | | |
125 | 7D | 175 | } | |
126 | 7E | 176 | ~ | |
127 | 7F | 177 | DEL |
Extended Character Set
Dec | Hex | Unicode | 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 Excel VBA ASC Function?
The main use of Excel Code Function is to convert alphabet into number. For example, you may want to know if a string contains A to Z, you can simply check if ASCII code is between 65 to 90, same for symbols.
Another use is to check unknown text. Some text looks like a space but underneath it may be something else, which is caused by conversion of other database type to Excel. After checking the ASCII code of that string, you can use Replace function to get rid of it.
Syntax of Excel VBA ASC Function
ASC(text)
Text The text which you want to convert into ASCII code
Note that ASC Function only returns the ASCII code of the first character in the text.
In Excel worksheet, ASC Function is called Code.
Example of Excel ASC Function
VBA Code | Result | Explanation |
ASC(“A”) | 65 | |
ASC(“Z”) | 90 | |
ASC(UCASE(Range(“A1”).Value))>=65 AND ASC(UCASE(Range(“A1”).Value))<=90) | TRUE (assume A1 contains text “B”) | Check if the first text in Cell A1 is an alphabet |
Loop through each character in a text to see if the any character contains an alphabet, disregard case sensitivity.
Public Function wCheckAlphabet(var) For i = 1 To Len(var) If Asc(Mid(UCase(var), i, 1)) >= 65 And Asc(Mid(UCase(var), i, 1)) <= 90 Then wCheckAlphabet = True Exit Function Else wCheckAlphabet = False End If Next i End Function
Outbound References
https://support.office.microsoft.com/en-us/article/CODE-function-daabc849-79e2-4661-8145-0b33c8397d4b?CorrelationId=2f7d4c56-6976-4a7f-948b-38b2b1da0be1&ui=en-US&rs=en-001&ad=US
Excel VBA Asc Function
The Asc function in VBA returns an integer value representing a character code corresponding to the function’s first character of a supplied string (string provided as argument/parameter). It can be used or given in a macro code generally entered via Visual Basic Editor.
We can use the Excel environment in which the macro runs in the Visual Basic Editor (VBE) to edit and debug the macro codes. It holds the macro code and links it to the Excel workbook.
The integer value returned by the Asc function is the corresponding ASCII character code in VBA. ASCII (American Standard Code for Information Interchange) is a 7-bit character encoding that has a total of 128 characters defined in it, including Latin alphabets, ten Arabic numerals, some punctuation marks, and control characters. It does not include diacritical characters as they require a minimum space of 8-bit for encoding. We can perform this 8-bit coding with ANSI (American National Standards Institute), which has 256 characters defined. ANSI is also called extended ASCII.
You are free to use this image on your website, templates, etc, Please provide us with an attribution linkArticle Link to be Hyperlinked
For eg:
Source: VBA Asc (wallstreetmojo.com)
Syntax of VBA Asc Function
The general syntax for the ASC function is as follows:
The ASC formula syntax has the following argument:
String: Required. It represents the text string whose first character’s corresponding character code is desired and returned.
If the string supplied has only one character, then the function returns the numeric character code for that character itself.
Examples of Excel VBA Asc
Let us see below how we can use the Asc in Excel VBA.
You can download this VBA Asc Function Excel Template here – VBA Asc Function Excel Template
Example #1
We have an Excel file containing some strings. We wish to use the Asc function with these strings. But, first, let us see the strings contained in the file:
We use the Asc function in VBA in a macro that can be written in the Visual Basic Editor and can be accessed as follows:
First, go to “Developer,” and then click on “Macros.”
Now, create a macro name: Under “Macro Name,” write the name of the macro desired to be created and select PERSONAL.XLSB in the dropdown of ‘Macros In.’ We can store the macros in a personal workbook, a hidden workbook that opens in the background whenever we start Excel. Selecting PERSONAL.XLSB would save the macros in the Personal workbook, thus making the macro always available since the personal workbook is not system/file specific.
Click on “Create.”
It would open a window with a VBA subprocedureSUB in VBA is a procedure which contains all the code which automatically gives the statement of end sub and the middle portion is used for coding. Sub statement can be both public and private and the name of the subprocedure is mandatory in VBA.read more in Visual Basic Editor as follows:
Now, define the variable Result1
Code:
Sub Code() Dim Result1 End Sub
Now, assign the variable Result1 with the formula to return the character code of the string:
Code:
Sub Code() Dim Result1 Result1 = Asc("Raj") End Sub
Now, the resultant value of Result1 can be displayed and returned using a VBA message boxVBA MsgBox function is an output function which displays the generalized message provided by the developer. This statement has no arguments and the personalized messages in this function are written under the double quotes while for the values the variable reference is provided.read more (MsgBox) as follows:
Code:
Sub Code() Dim Result1 Result1 = Asc("Raj") MsgBox Result1 End Sub
Now, when we run this code manually by clicking on “Run” at the top of the window or by pressing F5, we get the character code of the first letter of the string: “Raj,” displayed in a message box as follows:
So, we can see in the above screenshot that on running the macro, “82” is returned in a message box. It implies that the character code for “R” is 82.
Now, in the above example, we wish to find the character code for the string: “Karan.” To do this, we follow the same steps as above.
Instead of Raj, we will write Karan to get its character code in the code.
Code:
Sub String2() Dim Result2 Result2 = Asc("Karan") MsgBox Result2 End Sub
Now, we run this code manually or by pressing F5, and we get the character code of the first letter of the string: “Karan,” displayed in a message box as follows:
So, we can see in the above screenshot that on running the macro, “75” is returned in a message box. It implies that the character code for ‘K’ is 75.
Now, let us see how the result changes for the remaining strings:
Code:
Sub String3() Dim Result2 Result2 = Asc("Heena") MsgBox Result2 End Sub
Sub String4() Dim Result2 Result2 = Asc("Arun") MsgBox Result2 End Sub
Sub String5() Dim Result2 Result2 = Asc("A") MsgBox Result2 End Sub
Sub String6() Dim Result2 Result2 = Asc("a") MsgBox Result2 End Sub
On running these sub-procedures one by one, the following character codes return in the message box (one at a time, respectively). It is the list of corresponding values returned for the above strings.
So, as the above screenshot, we can see that the ASC function returns the character code as 65 for the string: “Arun” and the string: “A” because the character code returned is the VBA ASCII or equivalent character code for the first letter of the string in case the string is more than one character. Hence, 65 returns for both as the initial or first character of the string: “Arun” is also “A.”
Example #2
If the string supplied as parameter/argument to the VBA ASC function is an empty/blank string (or a string with no characters), then the function returns a run-time error.
The following code explains the same.
Sub blank() Dim result result = Asc("") MsgBox (result) End Sub
When we run this code, we get the run-time error as follows.
So, we can see in the above screenshot that when the string supplied as a parameter or argument to the ASC function is blank/empty, the function returns a run-time error.
Things to Remember
- The string supplied to the VBA ASC function can be any valid string expression.
- The Asc function is case-sensitive.
- The integer value returned by the Asc function is in the range of 0-255.
- The ASCII codes in VBA for A-Z are 65-90, and for a-z are 97-122.
- The name given to a macro or sub-procedure cannot be the name of some default function in VBA. If named so, then the sub-procedure will show an error.
Recommended Articles
This article has been a guide to VBA Asc. Here, we discuss examples of the Asc function in VBA to return ASCII Character codes, examples, and downloadable Excel templates. Below you can find some useful Excel VBA articles: –
- Goal Seek in VBA
- VBA Chr
- VBA StrConv Function
- Use Char Function In Excel
- VBA StatusBar
This Excel tutorial explains how to use the Excel ASC function with syntax and examples.
Description
The Microsoft Excel ASC function returns the ASCII value of a character or the first character in a string.
The ASC function is a built-in function in Excel that is categorized as a String/Text Function. It can be used as a VBA function (VBA) in Excel. As a VBA function, you can use this function in macro code that is entered through the Microsoft Visual Basic Editor.
Syntax
The syntax for the ASC function in Microsoft Excel is:
Asc( string )
Parameters or Arguments
- string
- The specified character to retrieve the ASCII value for. If there is more than one character, the function will return the ASCII value for the first character and ignore all of the characters after the first.
Returns
The ASC function returns a numeric value.
Applies To
- Excel for Office 365, Excel 2019, Excel 2016, Excel 2013, Excel 2011 for Mac, Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000
Type of Function
- VBA function (VBA)
Example (as VBA Function)
The ASC function can only be used in VBA code in Microsoft Excel.
Let’s look at some Excel ASC function examples and explore how to use the ASC function in Excel VBA code:
Asc ("W") Result: 87 Asc ("Wednesday") Result: 87 Asc ("x") Result: 120
For example:
Dim LResult As Integer LResult = Asc ("W")
In this example, the variable called LResult would now contain the value 87.
View a listing of the ASCII values.