O'Reilly logo

VB & VBA in a Nutshell: The Language by Paul Lomax

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Asc, AscB, AscW Functions

Named Arguments

No

Syntax

Asc(string)
AscB(string)
AscW(string)

string

Use: Required

Data Type: String

Any expression that evaluates to a string.

Return Value

An integer that represents the character code of the first character of the string. The range for the returned value is 0–255 on non-DBCS systems, but –32768–32767 on DBCS systems.

Description

Returns the ANSI or Unicode character code that represents the first character of the string passed to it. All other characters in the string are ignored. Use AscB with Byte data and AscW on Unicode (DBCS) systems.

Rules at a Glance

  • The string expression passed to the function must contain at least one character, or a runtime error (either "Invalid use of Null" or "Invalid procedure call or argument") is generated.

  • Only the first character of the string is evaluated by Asc, AscB, and AscW.

  • Use the AscW function to return the Unicode character of the first character of a string.

  • Use the AscB function to return the first byte of a string containing byte data.

Example

Dim sChars As String
Dim iCharCode As Integer
    
sChars = TextBox1.Text
If Len(sChars) > 0 Then
   iCharCode = Asc(sChars)
   If iCharCode >= 97 And iChar <= 122 Then
      MsgBox "The first character must be uppercase"
   End If
End If

Programming Tips and Gotchas

  • Always check that the string you are passing to the function contains at least one character using the Len function, as the following example shows:

    If Len(sMyString) > 0 Then iCharCode = Asc(sMyString) ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required