VBA/Excel/Access/Word/Data Type Functions/Data Type Convert

Материал из VB Эксперт
Перейти к: навигация, поиск

Use CInt to convert input value to integer

Sub cintDemo()
    Dim varMyInput
    Dim intMyVar As Integer
    varMyInput = InputBox("Enter an integer:", "10 Is True, Other Numbers Are False")
    intMyVar = CInt(varMyInput)
    MsgBox CBool(intMyVar = 10)
End Sub

Using the Asc Function to Return a Character Code

"Use the Asc function to return the character code for the first character of the current selection
"Using the Val Function to Extract a Number from the Start of a String
Sub valDemo()
    Dim Address1 As String
    Address1 = "asdf 123"
    Dim StreetNumber As Integer
    StreetNumber = Val(Address1)
    Debug.Print StreetNumber
End Sub

Using the Str Function to Convert a Value to a String

Sub Age()
    Dim intAge As Integer, strYourAge As String
    intAge = InputBox("Enter your age:", "Age")
    strYourAge = "Your age is" & str(intAge) & "."
    MsgBox YourAge, vbOKOnly + vbInformation, "Age"
End Sub

VBA"s Functions for Complex Data Conversion

Function(Arguments)             Returns         
Asc(string)                     The ANSI character code for the first character in the string.        
Chr(number)                     The string for the specified character code (a number between 0 and 255).        
Format(expression, format)      A variant containing expression formatted as specified by format. (You"ll see how Format works in "Using the Format Function to Format an Expression," later in the chapter.)        
Hex(number)                     the hexadecimal value of number.        
Oct(number)                     the octal value of number.        
RGB(number1, number2, number3)  the color value specified by number1, number2, and number3.        
QBColor(number)                 A Long containing the RGB value for the specified color.        
Str(number)                     A string representation of number.        
Val(string)                     The numeric portion of string

VBA"s Functions for Simple Data Conversion

Function(Arguments)      Data Type Returned         
CBool(number)            Boolean        
CByte(expression)        Byte        
CCur(expression)         Currency        
CDate(expression)        Date        
CDbl(expression)         Double        
CInt(expression)         Integer        
CLng(expression)         Long        
CSng(expression)         Single        
CStr(expression)         String        
CVar(expression)         Variant