The VBA CByte Function

Description

The VBA CByte function converts an expression into a Byte data type.

The syntax of the function is:

CByte( Expression )

Where the Expression argument is the expression that that you want to convert to a Byte.

The Byte data type can hold simple integer values between 0 and 255. Therefore, the supplied Expression must be able to be intepreted as (or converted into) an integer between 0 and 255.


VBA CByte Function Examples

In the following VBA code, the VBA CByte function is used to convert two different values into Byte data types.

' Convert Two Values Into Byte Data Types
Dim byte1 As Byte
Dim byte2 As Byte
byte1 = CByte( 10 )
' byte1 is now equal to the value 10
byte2 = CByte( 3.95 )
' byte2 is now equal to the value 4

After running the above VBA code, the variables byte1 and byte2 are equal to 10 and 4 respectively.

Note that the value 3.95 was rounded to the nearest integer before being converted to a Byte data type.


VBA CByte Function Errors

If you supply the CByte function with a numeric value that is less than 0 or greater than 255, you will get the error:

Run-time error '6': Overflow

VBA Run Time Error 6 Message Box


If you supply the CByte function with a String that cannot be converted to a number, you will get the error:

Run-time error '13': Type mismatch

VBA Run Time Error 13 Message Box