0% found this document useful (0 votes)
7 views

LESSON4 - Data - Date - Formart - Functions

The document discusses various data conversion functions in Visual Basic that allow conversion between different data types. It covers functions like CStr, Str, CDbl, Val, CInt, CLng, CBool and others and provides examples of how to use each one to convert between strings, doubles, integers, longs and booleans. It also discusses formatting functions like Tab, Space and Format that allow formatting numeric output in different styles like general number, fixed, standard, currency and percent formats.

Uploaded by

polycarpkamolo
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

LESSON4 - Data - Date - Formart - Functions

The document discusses various data conversion functions in Visual Basic that allow conversion between different data types. It covers functions like CStr, Str, CDbl, Val, CInt, CLng, CBool and others and provides examples of how to use each one to convert between strings, doubles, integers, longs and booleans. It also discusses formatting functions like Tab, Space and Format that allow formatting numeric output in different styles like general number, fixed, standard, currency and percent formats.

Uploaded by

polycarpkamolo
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 13

Data Conversion Function

When you’re working with many variables of different data types in an expression, the variable or expression on the right
hand side of the assignment operator must first be converted into the target type. Otherwise assignment will not be
possible. In some cases, Visual Basic does it for you. That means that you don’t need to write code to convert the data
types conversion is done automatically. But this doesn’t happen all the time
Conversion functions

The functions are CBool, CByte, CCur, CDate, CDbl, CDec, CInt, CLng, CSng, CStr, and CVar.
Val and Str functions are also used.

1. CStr: The Cstr function converts an expression to a string. This is useful when you’re displaying some numeric
values in a text box control.
Example:

Dim v1 As Double
Text1.Text = CStr(v1)
2. Str : The Str function converts a number to a string. It is similar to the Cstr function.
Example:
Dim str1 As String, m As Integer
str1 = Str(m)
3. CDbl: The CDbl function converts an expression into a Double. It also extracts the numeric value from a string.
Example: If you omit the CDbl function, the program will raise an overflow error.

Dim m As Integer, v As Double


m = 30887
v = CDbl(m) * 31880
Print v

Example:
Dim value As Double
value = CDbl(Text1.Text)
Print value + 1

Example:
Dim value As Double
value = CDbl("55")
Print value + 1
4. Val: Sometimes you can use the Val function instead of the CDbl function. Val function returns a Double value.
It only returns the numeric value contained in a string.

Example:

Dim l As Double
l = Val(Text1.Text)
5. CInt: The CInt function converts a number to integer.
Example:
Dim m As Integer
m = CInt(876.878) 'Returns 877 after roundin the no.
m = CInt(-2.7) 'Returns -3 after rounding the no.

The argument must be within the Integer range here.


876.878 and -2.7 are the arguments in the above code.

6. CLng: The CLng function converts to Long type.


Example:
Dim ln As Long
ln = CLng(1147483647.87656) 'Rounds up the value
Print ln
7. CBool: The CBool function converts an expression to Boolean Data type, i.e either True or False.
The value of zero is converted to False and all other numeric values are converted to True. The strings “True” and
“False” return True and False Boolean values respectively.
Example:

Dim B as Boolean
B=cbool(0) 'Returns False
B=cbool(1) 'Returns true
B=cbool(345) 'Returns True

NB: CByte, CSng, CVar,CCur,CDate and CDecimal functions convert to Byte, Sinle, Variant, Currency, Date and
Decimal values respectively. You can use these functions in the same way explained above.
Formatting Functions
Formatting output is an important part of programming so that the visual interface can be presented clearly to the users.
Data in the previous lesson were presented fairly systematically through the use of commas and some of the functions like
Int, Fix and Round. However, to better present the output, we can use a number of formatting functions in Visual basic.
The three most common formatting functions in VB are Tab, Space, and Format

(i) The Tab function

The synatx is Tab (n); x


The item x will be displayed at a position that is n spaces from the left border of the output form. There must be a
semicolon in between Tab and the items you intend to display (VB will actually do it for you automatically).

Example1

.Private Sub Form_Activate


Print "I"; Tab(5); "like"; Tab(10); "to"; Tab(15); "learn"; Tab(20); "VB"
Print
Print Tab(10); "I"; Tab(15); "like"; Tab(20); "to"; Tab(25); "learn"; Tab(20); "VB"
Print
Print Tab(15); "I"; Tab(20); ; "like"; Tab(25); "to"; Tab(30); "learn"; Tab(35); “VB"
End sub
The Output for example 1 is shown below:

(ii) The Space function


The Space function is very closely linked to the Tab function. However, there is a minor difference. While Tab (n) means
the item is placed n spaces from the left border of the screen, the Space function specifies the number of spaces between
two consecutive items. For example, the procedure
Example 2
Private Sub Form_Activate()
Print "Visual"; Space(10); "Basic"
End Sub
Means that the words Visual and Basic will be separated by 10 spaces

(iii) The Format function


The Format function is a very powerful formatting function which can display the numeric values in various forms. There
are two types of Format function, one of them is the built-in or predefined format while another one can be defined by the
users.

a) The format of the predefined Format function is


Format (n, “style argument”)
where n is a number and the list of style arguments is given in the table

Style argument Explanation Example

General Number To display the number without having Format(8972.234, “General


separators between thousands. Number”)=8972.234
Fixed To display the number without having Format(8972.2, “Fixed”)=8972.23
separators between thousands and rounds it up
to two decimal places.
Standard To display the number with separators or Format(6648972.265, “Standard”)=
separators between thousands and rounds it up 6,648,972.27
to two decimal places.
Currency To display the number with the dollar sign in Format(6648972.265, “Currency”)=
front, has separators between thousands as well $6,648,972.27
as rounding it up to two decimal places.
NB: Returns an expression formatted as a
currency value by using the currency symbol
defined in the system control panel.
Percent Converts the number to the percentage form and Format(0.56324, “Percent”)=56.32 %
displays a % sign and rounds it up to two
decimal places.

Example 12.3

Private Sub Form_Activate()


Print Format (8972.234, "General Number")
Print Format (8972.2, "Fixed")
Print Format (6648972.265, "Standard")
Print Format (6648972.265, "Currency")
Print Format (0.56324, "Percent")
End Sub
Now, run the program and you will get an output like the figure below:
(b) The syntax of the user-defined Format function is
Format (n, “user’s format”)
Although it is known as user-defined format, we still need to follows certain formatting styles. Examples of user-defined
formatting style are listed in Table 12.2

Example Explanation Output

Format(781234.57,”0”) Rounds to whole number without separators between 781235


thousands.
Format(781234.57,”0.0”) Rounds to 1 decimal place without separators 781234.6
between thousands.
Format(781234.576,”0.00”) Rounds to 2 decimal places without separators 781234.58
between thousands.
Format(781234.576,”#,##0.00”) Rounds to 2 decimal places with separators between 781,234.58
thousands.
Format(781234.576,”$#,##0.00”) Shows dollar sign and rounds to 2 decimal places $781,234.58
with separators between thousands.
Format(0.576,”0%”) Converts to percentage form without decimal places. 58%
Format(0.5768,”0.00%”) Converts to percentage form with 2 decimal places. 57.68%

Table 12.2: User-Defined Formatting Functions

Example 12.4
Private Sub Form_Activate()
Print Format(781234.57, "0")
Print Format(781234.57, "0.0")
Print Format(781234.576, "0.00")
Print Format(781234.576, "#,##0.00")
Print Format(781234.576, "$#,##0.00")
Print Format(0.576, "0%")
Print Format(0.5768, "0.00%")
End Sub
Date And Time Functions
Recall the VB keywords that reference the current date and/or time:

 Now A vb6 date function that returns the current date and time together
 Date Returns the current date
 Time Returns the current time

For the examples that follow, assume that the current Date/Time (Now) is Friday, August 31, 2001at 9:15:20 PM.

The following functions isolate the date portion and time portion, respectively, of a Date/Time value:

Function Description

DateValue Returns the date portion of a Date/Time value, with the time portion "zeroed out". (Note:
When the vb6 time portion of a date/time variable is "zeroed out", the time would be
interpreted as 12:00 AM.)

Example:

Dim dtmTest As Date


dtmTest = DateValue(Now)

At this point, the date portion of dtmTest is 8/31/2001, with a time portion of 0 (12:00
AM midnight).

TimeValue Returns the time portion of a Date/Time value, with the date portion "zeroed out". (Note:
When a date/time variable is "zeroed out", the date will actually be interpreted as December
30, 1899.)

Example:

Dim dtmTest As Date


dtmTest = TimeValue(Now)

At this point, the time portion of dtmTest is 9:15:20 PM, with a date portion of 0
(12/30/1899).

The following functions are used to isolate a particular part of a vb6 date:

Function Description

WeekdayName Returns a string containing the weekday name ("Sunday" thru "Saturday"), given a numeric
argument with the value 1 through 7.
Example:
strDOW = WeekdayName(6) ' strDOW = "Friday"

The WeekdayName function takes an optional, second argument (Boolean) indicating


whether or not to abbreviate the weekday name. By default, the second argument is False,
meaning do not abbreviate and return the full name. If True, the first three letters of the
weekday name will be returned:

Example:
strDOW = WeekdayName(6, True) ' strDOW = "Fri"

You can nest the Weekday function within the WeekdayName function to get the weekday
name for a given date:

Example:
strDOW = WeekdayName(Weekday(Now)) ' strDOW = "Friday"

Month Returns a number from 1 to 12 indicating the month portion of a given date.

Example:
intMonth = Month(Now) ' intMonth = 8

MonthName Returns a string containing the month name ("January" thru "December"), given a numeric
argument with the value 1 through 12.

Example:
strMoName = MonthName(8) ' strMoName = "August"

The MonthName function takes an optional, second argument (Boolean) indicating whether
or not to abbreviate the month name. By default, the second argument is False, meaning do
not abbreviate and return the full name. If True, the first three letters of the month name will
be returned:

Example:
strMoName = MonthName(8, True) ' strMoName = "Aug"

You can nest the Month function within the MonthName function to get the month name for a
given date:

Example:
strMoName = MonthName(Month(Now)) ' strMoName = "August"

Day Returns a number from 1 to 31 indicating the day portion of a given date.

Example:
intDay = Day(Now) ' intDay = 31
Year Returns a number from 100 to 9999 indicating the year portion of a given date.

Example:
intYear = Year(Now) ' intYear = 2001

The following functions are used to isolate a particular part of a time:

Function Description

Hour Returns an integer specifying a whole number between 0 and 23 representing the hour of the
day.

Example:
intHour = Hour(Now) ' intHour = 21 (for 9 PM)

Minute Returns an integer specifying a whole number between 0 and 59 representing the minute of
the hour.

Example:
intMinute = Minute(Now) ' intMinute = 15

Second Returns an integer specifying a whole number between 0 and 59 representing the second of
the minute.

Example:
intSecond = Second(Now) ' intSecond = 20

To demonstrate the date functions shown thus far, set up a "Try It" project, and place the following code in the
cmdTryIt_Click event:

Private Sub cmdTryIt_Click()

Print "Now:"; Tab(30); Now


Print "Using DateValue:"; Tab(30); DateValue(Now)
Print "Using TimeValue:"; Tab(30); TimeValue(Now)
Print "Using Weekday:"; Tab(30); Weekday(Now)
Print "Using WeekdayName:"; Tab(30); WeekdayName(Weekday(Now))
Print "Using WeekdayName (abbrev.):"; Tab(30); WeekdayName(Weekday(Now), True)
Print "Using Month:"; Tab(30); Month(Now)
Print "Using MonthName:"; Tab(30); MonthName(Month(Now))
Print "Using MonthName (abbrev.):"; Tab(30); MonthName(Month(Now), True)
Print "Using Day:"; Tab(30); Day(Now)
Print "Using Year:"; Tab(30); Year(Now)
Print "Using Hour:"; Tab(30); Hour(Now)
Print "Using Minute:"; Tab(30); Minute(Now)
Print "Using Second:"; Tab(30); Second(Now)

End Sub

Run the project and click the "Try It" button. The output should look similar to the following:

Download the VB project code for the example above here.

The DatePart Function

The generic DatePart function returns an Integer containing the specified part of a given date/time value. Thus, it
incorporates the functionality of the Weekday, Month, Day, Year, Hour, Minute, and Second functions. In addition, it can
used to get the quarter of a given date (1 through 4) , the "Julian" date (the day of the year from 1 to 366), and the week
number (1 through 53).

Syntax:
DatePart(interval, date[,firstdayofweek[, firstweekofyear]])

The DatePart function syntax has these parts:

Part Description

Interval Required. String expression that is the interval of time you want to return.
The string expression can be any of the following:

Expression Description Possible Range of Values

"yyyy" Year 100 to 9999

"q" Quarter 1 to 4

"m" Month 1 to 12

"y" Day of year 1 to 366 (a "Julian" date)

"d" Day 1 to 31

"w" Weekday 1 to 7

"ww" Week 1 to 53

"h" Hour 0 to 23

"n" Minute 0 to 59

"s" Second 0 to 59

Date Required. Date value that you want to evaluate.

Firstdayofweek Optional. A constant that specifies the first day of the week. If not specified, Sunday is
assumed.

firstweekofyear Optional. A constant that specifies the first week of the year. If not specified, the first week is
assumed to be the week in which January 1 occurs.

To demonstrate DatePart, set up a "Try It" project, and place the following code in the cmdTryIt_Click event:

Private Sub cmdTryIt_Click()


Print "Current date/time is: "; _
Format$(Now, "Long Date"); _
Spc(1); _
Format$(Now, "Long Time")
Print "*** DatePart Function Examples ***"
Print "Using 'yyyy':"; Tab(20); DatePart("yyyy", Now)
Print "Using 'q':"; Tab(20); DatePart("q", Now)
Print "Using 'm':"; Tab(20); DatePart("m", Now)
Print "Using 'y':"; Tab(20); DatePart("y", Now)
Print "Using 'd':"; Tab(20); DatePart("d", Now)
Print "Using 'w':"; Tab(20); DatePart("w", Now)
Print "Using 'ww':"; Tab(20); DatePart("ww", Now)
Print "Using 'h':"; Tab(20); DatePart("h", Now)
Print "Using 'n':"; Tab(20); DatePart("n", Now)
Print "Using 's':"; Tab(20); DatePart("s", Now)

End Sub

Run the project and click the "Try It" button. The output should look similar to the following:
Download the VB project code for the example above here.

Piecing Separate Numbers Together to Form a Date or Time Value

In the previous examples, we saw ways to isolate parts of a date/time value. What if you need to go the "other way"? If
you have the separate parts of a date/time value in different variables and want to piece them together to formulate a date
or time, there are two functions you can use to do this:DateSerial and TimeSerial.

The DateSerial takes three numeric arguments: year, month, and day respectively. It returns a date based on those values.
Example:

Dim intYear As Integer


Dim intMonth As Integer
Dim intDay As Integer
Dim dtmNewDate As Date

intYear = 2001
intMonth = 9
intDay = 2

dtmNewDate = DateSerial(intYear, intMonth, intDay)


' returns 9/2/2001

The TimeSerial takes three numeric arguments: hour, minute, and second respectively. It returns a time based on those
values.
Example:
Dim intHour As Integer
Dim intMinute As Integer
Dim intSecond As Integer
Dim dtmNewTime As Date

intHour = 11
intMinute = 34
intSecond = 44

dtmNewTime = TimeSerial(intHour, intMinute, intSecond)


'returns 11:34:44 (AM)

You might also like