You are on page 1of 17

Visual Basic 6 Library Functions – String Type

These are the Built in Functions provided by Visual Basic. VB offers a rich set of built-in-functions for
manipulating strings, numbers, dates and time. Built in functions are important and useful as they
cut down effort and time, if one has to write the entire program all over. This tutorial is going to
cover some of the important and commonly used string functions available in the Visual Basic
Library.

String Functions
The string functions allow you to work with strings in numerous ways such as changing cases,
extracting characters from a string, determining whether a character is a part of a string etc. etc.

1. The LCase and UCase Functions

these two functions convert strings to all lower or all upper case. The LCase( ) functions converts a
string into all lower case and UCase( ) does exactly the opposite. These functions might be useful if
you want to compare strings.

The Syntax would be :-


view source

print?
1 LCase(String)
2 UCase(String)

Consider the following example :-


view source

print?
1 Print UCase(“hello world”)

The output would be HELLO WORLD.

Similarly,
view source

print?
1 Print LCase(“StuDEnts”)

Will produce string students.

Note that both the functions work ignorant of the fact whether the string has upper or lower case
characters or not. They simply convert all the characters to upper or lower case respectively.

Now consider the following example.

Example 1.1
Obtain text from textbox txtLocation and determine whether the user lives on Earth or not.
Remember that the user can enter the location in any possible case combination. You should be
able to compare with all cases .
view source

print?
01 Private Sub txtLocation_Change( )
02 Dim Loc As String
03
04 Loc = “earth”
05
06 If UCase(txtLocation.Text) = UCase(Loc) then
07 MsgBox “So you live on earth, welcome humanoid! ”
08 End if
09
10 End sub

Essential Fact:
Note that it is essential for both stings to be equal in case as WELL as in LENGTH. Try running the
Above code with a trailing blank in the text box, you wont get any result. Handling such problems is
discussed further in the tutorial. You can also use LCase function (on both sides of course) instead
of the UCase function that has been used in the above example. Always remember that you can
compare strings in two ways; case – ignorant or non ignorant, depending on the need.

2. The Len Function

This Function gives you the length of the string i.e. how many characters long the string is. All the
characters are counted ( punctuation, numbers, alphabets, special characters and blank spaces.
Etc)

The Syntax is:-


view source

print?
1 Len(String)

Consider this:
view source

print?
1 Dim sAddress As String, iResult as Integer
2 sAddress = “125 Princeton Street”
3 iResult = Len(sAddress)

After the above code is executed the variable iResult stores the value 20 , which is inclusive of the
blank spaces in the sAddress variable.

This function can be used very effectively in allowing minimum and maximum length for a value.
For example, a password field may have a minimum of 6 characters and a maximum of 20
characters, and this can be verified by the Len( ) Function.

3. The Trim, LTrim and RTrim Functions.

These functions remove leading (LTrim function) or trailing(RTrim Function) from a string. These
functions don’t affect any spaces between words. The Trim( ) function simply accomplishes both
LTrim( ) and RTrim( ) function, i.e. removes all leading and trailing blanks.

Syntax
view source
print?
1 LTrim(String)
2 RTrim(String)
3 Trim(String)

Users may inadvertently type spaces into a text box, and you can use these functions to account for
that, but mostly the Trim( ) function is used with fixed-Length strings, user defined types, and
Random Access Files.

Now consider the following code example:


view source

print?
1 sResult = LCase(Trim(“ EXCEL “)

the variable sResult will store the value “excel” in it. Here we’ve used a function as an
argument for another function. This is commonly done and an efficient way to program.

Now let’s re-write the program of example 1.1


This time note that the blank spaces in front or back of text should not affect the result.
view source

print?
01 Private Sub txtLocation_Change( )
02
03 Dim Loc As String
04 Loc = “earth”
05
06 If UCase(Trim(txtLocation.Text)) = UCase(Loc) then
07 MsgBox “So you live on earth, welcome humanoid! ”
08 End if
09
10 End sub

See, now the code works irrespective of the blank spaces in front or back of the main text.

4. Left and Right Functions

These are two functions that are used to extract a certain number of characters from the leftmost or
rightmost portions of a string. These functions require two arguments L the original string, and the
number of characters to extract from that string.

Syntax:
view source

print?
1 Left(string, no-of characters)
2 Right(string, no-of characters)
Now consider the following example code.
view source

print?
1 Dim Pname As String
2 Pname = “Samuel Williams”
3 Print Left(Pname, 6)
4 Print Right(Pname, 8)

The above code produces the result:

Quote

Samuel
Williams

The first word Samuel is printed because of the statement


view source

print?
1 Print Left(Pname, 6)

see that it has been assigned to take the Pname string containing “Samuel Williams” and
extract 6 leftmost characters from it. Similarly the code:
view source

print?
1 Print Right(Pname, 8)

extracts 8 rightmost characters from the Pname string.

5. Mid Function and Mid Statement.


Mid function is used to extract characters from the middle of a string, we need three arguments
here: the Original String, the place to Start Extracting characters, and the number of characters to
extract.

Syntax
view source

print?
1 Mid(String, start-position, no-of-characters)

for example, the following code :


view source

print?
1 Print Mid("Green Day Rocks", 7, 3)

will print “Day”, starting from the 7th character extracting 3 characters including the start
position character. Try changing the start position and no of characters values in the function and
notice the different results obtained.
Also note that all characters are included in the operation.

The Mid Statement not only extracts the characters, but also replaces them with the text you
specify. Since this is a statement and not a function, you don’t get a result, rather the action is
completed for you,

For example, in the following code, an unscrupulous person typed in the variable sInput that
“Green Day Sucks”, you can change it to “Green Day Rocks” by the following Code:

view source

print?
1 sInput = "Green Day Sucks"
2 Print sInput
3 Mid(sInput, 11, 5) = "Rocks"
4 Print sInput

here we see that the position of “S” in “Sucks” is at 11 position from start, in the string
“Green Day Sucks”, therefore we input “11” as start position to replace, and since there
are 4 preceding unwanted characters, we input “5” as the total number of characters to be
replaced. The ‘=’ character indicates by which string to replace which we write on the right
hand side, which is “Rocks”

SEE the difference in the First Print and the second print. And by applying your own Kode LogiK, you
can specify the start position, the number of characters to replace and the text to put in the original
place.

Now consider an example that uses both Mid( ) function as well as Mid Statement.

-Write a function namely AltCap that receives a String argument and returns the string wherein
each alternate character is in Uppercase.

Now add this code in the general declaration part of a form.


view source

print?
01 Public Function AltCap (ByRef sInput As String) As String
02
03 Dim i As integer, sCurrentChar As String
04 For i = 1 to Len(sInput)
05
06 sCurrentChar = Mid(sInput, i, 1) ‘Mid Function Used
07
08 if i Mod 2 = 0 then
09 Mid(sInput, i, 1) = LCase(sCurrentChar) ‘ Mid Statement Used.
10 Else
11 Mid(sInput, i, 1) = UCase(sCurrentChar) ‘ Mid Statement Used.
12 End If
13
14 Next i
15 AltCap = sInput
16
17 End Function

Now call the Function in a Command Button’s click( ) event.


view source

print?
1 Private Sub Command1_Click()
2 Dim myString As String
3 myString = "I want to be a leet"
4 myString = AltCap(myString)
5 Print myString
6 End Sub

The output would be produced as :


I WaNt tO Be a lEeT

Note that blank spaces are also “uppercased” in the function that we have used, which
obviously doesn’t have any effect.

6. InStr Function

The InStr function searches for strings within strings.

Syntax
view source

print?
1 InStr([start],string1,string2,[Compare]) ‘[ ] means optional.

Where

Quote

Start
Is a numeric expression that sets the starting position for each search, if omitted, the search begins
at the first character of the string.

String1
Is the String in which to search.

String2
Is the string to be searched for in the “string1” string.
Compare
Specifies the type for string comparison. “0” for case sensitive search and “1” for case
insensitive search.

Bringing to your attention:

Quote

there are two ways to compare strings – case sensitive and case insensitive.
> case sensitive is a Binary Comparison
e.g. string “VB” and string “vb” are not equal in this case.

>case insensitive is a Text Comparison.


e.g. string “VB” and string “vb” are equal in this case.

By default VB6 will use the Binary method to compare strings unless explicitly specified.

Now Consider the Following Code.


view source

print?
01 Dim SearchString, SearchChar, MyPos
02 ‘this is the String to Search in
SearchString = “the earth is the third planet in the Solar
03
system”
04 ‘this is the String to Search for
05 SearchChar = “S”
06
07 ‘ Textual Comparison starting at position 1 returns 12
08 MyPos = InStr( 1,SearchString, SearchChar,1)
09 Print MyPos
10
11 ‘ Binary Comparison starting at position 1 returns 38
12 MyPos = InStr( 1,SearchString, SearchChar,0)
13 Print MyPos
14
‘If you simply omit the compare and start argument, it will return
15
38
16
17 MyPos = InStr( SearchString, SearchChar)
18 Print MyPos
19
20 ‘Now to search for a Sting that doesn’t exist.
21 MyPos = InStr( 1,SearchString,”X”,1)
22 Print MyPos
23 ‘ ^^Returns ‘0’

InStr is a function and will return the position of the first occurrence of the search string . if the
string is not found then it will return ‘0’.

Something more

Quote

InStrRev( ) is a related function here. It works similar to the InStr function, but it performs the
search BACKWARDS.

7. Space Function

this function by itself produces a certain number of spaces.

Syntax
view source

print?
1 Space(number)
2 ‘Number argument is the number of spaces you want in the string.

Consider the following example code.


view source

print?
1 Dim MyString
2 MyString = “HelloWorld”
3 Print MyString
‘ this line inserts 10 blank spaces in between ‘Hello’ and
4
‘World’
5 MyString = “Hello”& Space(10) & “World”
6 Print MyString

the best use of Space( ) is to clear fixed length strings.


sRecord = Space(128)

8. String Function

this function is used for producing a string with certain number of repeating characters.
Syntax
view source

print?
1 String(number,character)
2 ‘Number >> number of characters to be repeated
3 ‘character is the character to repeat
4 ‘or you can also input character code

ForExample, the following code


view source

print?
1 sResult = String(10,65)
2 ‘65 is the character code for uppercase “A”

will return “AAAAAAAAAA”

Now consider this :


view source

print?
1 Dim MyString
2 MyString = String(5, “*”) ‘Returns “*****”
3
4 ‘Character code for “*” is 42
5 MyString = String(5, 42) ‘Returns “*****”
6
7 MyString = String(10, “ABC”) ‘ returns “AAAAAAAAAA”
8 Print MyString

Quote

Remember that no matter how long the string you enter in the character argument, it will always
select the first character of that string. So entering “ABC” or “ABCDEFGH” wont matter
much, as “A” will be selected in both cases.

9. Str Function

this function converts a number into equivalent string.


view source

print?
1 Syntax
2 Str(number)
‘The Required number argument is a long containing any valid
3
numeric exp<B></B>ression.
Quote

when numbers are converted to strings, a leading space is always reserved for the sign of number.
If number is positive, then the returned string contains a leading space and the plus sign is implied,
else a ‘-’ sign is put in front of the number.

The following example uses the Str Function to return a sting representation of a number.
view source

print?
1 Dim MyString
2 MyString = Str(1302)
3 Print MyString ‘Returns “ 1302”
4
5 MyString = Str(-12503.54)
6 Print MyString ‘Returns “-12503.54”
7
8 MyString = Str(234.007)
9 Print MyString ‘Returns “ 234.007”

10. Asc Function

This function is used to get a character’s equivalent ASCII code


Syntax
view source

print?
1 Asc(String)

Quote

Normally you would use a single character enclosed in quotes or one character resulting from
another function, but using a multi character string doesn’t cause an error; the function will
simply take the first character of the string.

For Example the following code will print 68, the ASCII code of character “D”.
view source

print?
1 sObject = “Donkey”
2 iResult = Asc(sObject)
3 Print iResult

11. Chr Function


This function returns a String containing the character associated with the specified character code.

The Syntax
view source

print?
1 Chr(charcode)

where the required charcode argument is a Long that identifies a character.

Quote

Numbers from 0 – 31 are the same as standard, non preintable ASCII codes. For example,
Chr(10) returns a linefeed character. The normal range for charcode is 0 – 225. However on
DBCS systems, the actual range for charcode is from -32768 to 65535.

Now consider the following example:


view source

print?
1 Dim MyChar
2 MyChar = Chr(65) ‘Returns “A”
3 MyChar = Chr(97) ‘Returns “a”
4 MyChar = Chr(62) ‘Returns “>”
5 MyChar = Chr(37) ‘Returns “%”

12. StrReverse Function


This Function returns a string in which the order of a specified string is reversed. Its Syntax is
view source

print?
1 StrReverse(String1)
The scope (or visibility) of a variable is the portion of code from which that variable
can be accessed. For example, a variable declared with the Public attribute in a BAS
module is visible—and can therefore be read from and written to—from anywhere in
the application, whereas if the variable is declared Private, it's visible only from
within that BAS module.
• The lifetime of a variable is the time period during which that variable stays alive
and uses memory. The lifetime of the Public variable described in the previous
paragraph coincides with the application's life, but in general this isn't always the
case. For instance, a local dynamic variable in a procedure is created each time
Visual Basic executes that procedure and is destroyed when the procedure exits

At the same time you do not want to open and close recordsets. So if you call only
one procedure at a time then local is the correct answer. But if you always call three
procedures. Then neither of you are correct. Here is the proper solution if you
always use all three procedures in a row.

public sub executeProcedures()


dim rs as dao.recordset
set rs = ....
call procedure1(rs)
call procedure2(rs)
call procedure3(rs)
end sub

The scope is local to executeProcedures, and the lifetime ends at the end of
execution, and the rs is opened only once.
if you want to share a value amongst multiple forms AND you cannot guarantee that
one particular form will always be open during the sharing, you need a global
variable.

last item on the left of your database window Tables/Queries/Forms...... is Modules.

new module

global myGlobalVariable as long 'or whatever it is

downside of modules is that the first reference to a sub/func/var/const in a global


module loads the entire module into memory and it stays there until you quit the
application ...so you should try to minimise the number of globals you use.

if you do have a form that will always be open during the sharing process, it is tidier
to put your shared variable on that form (when the form is closed, memory is
cleared). at the top of the code, just before the first sub/func use
public myPublicVariable as long 'or whatever

Data Control for Visual Basic 6.0 Users


Visual Studio 2005
Other Versions

The Visual Basic 6.0 Data control is used as a mechanism for binding controls to a
database using DAO. Visual Basic 2005 has no equivalent for the Data control; the data-
binding architecture has changed and DAO is no longer supported. For more information,
see Data Access for Visual Basic 6.0 Users.

The Data control also provides an interface for navigating data, with buttons for moving
back and forth through rows in a database table. Visual Basic 2005 has an equivalent
control, the BindingNavigator control, which also contains buttons for adding and deleting
rows.

The Visual Basic Data Control can be used to write VB programs that can easily
manipulate databases created with Microsoft Access, FoxPro, dBase, Paradox, Btrieve,
Excel, or any ODBC*-compliant database, such as Oracle and SQL Server databases.
(*Open DataBase Connectivity). Visual Basic's native database format is Access, and the
Access "Jet" Database Engine is included with VB.
The Data Control has two key properties: DatabaseName is the filename of a compatible
database. RecordSource is the name of a table in the database, or the result of a SQL
(Structured Query Language) query.

Many VB controls are "data-aware", and can be "bound" to the Data Control. That is, as
you move from record to record using the Data Control, the bound controls show you the
field contents of each record. Bound controls generally have a DataSource property,
which should be the name of the Data Control, and a DataField property, which is the
name of the field you want displayed in that control.

1. To use a Data Control, first select the control from the toolbox and draw it on
your form. Its default name is Data1, which we'll use in the examples below.
2. In the properties window, set the DatabaseName property to the filename of the
database you want. Click on the ellipsis button (...) to use a "file open" dialog.
3. Set the RecordSource property to the name of a database table within the database
you selected. If you've already selected a database as in step 2, a drop-down list of
choices will be provided.
4. Put a Text Box on your form. (You can also use other data-aware controls, such
as CheckBoxes, Labels, Image controls, and PictureBoxes.)
5. Set the DataSource property for the text box to Data1.
6. Set the DataField property for the text box to the field you wish to display. If
steps 2-5 have been accomplished with a valid database, a drop-down list of
choices will be provided.
7. You may wish to put a Label control in front of the text box with the fieldname
selected in step 6.
8. Repeat steps 4-7 for each field you wish to display.
9. Run your application.

Another Way: Grid View

1. Start a new project and put a Data Control on the form


2. Set the DatabaseName property of Data1
3. Set the RecordSource property
4. From the Project menu, choose Components. Check either the Microsoft
FlexGrid control or the Microsoft DataBound Grid control. The FlexGrid is read-
only, but it has features such as data-pivoting. The DataBound Grid control
allows the user to edit its fields.
5. Put a DBGrid or FlexGrid control on your form. Make it fairly large.
6. Set the DataSource property of the grid to Data1
7. Run your program

Have you noticed that we have yet to write ANY code?


The Data Control's RecordSource and RecordSet Properties

The RecordSource tells where the data will come from. You can think of the Recordset
property as the actual data that you've requested using the RecordSource.

The RecordSource can be the name of a table in a database, the name of an Access
database query, or the text of a SQL query. If you change the RecordSource at run-time,
you must use the method Data1.Refresh to actually go out and get the data and assign it
to the RecordSet.

Once you have a RecordSet, you can use the following methods in your program:

RecordSet Methods
Data1.RecordSet.AddNew
adds a new record to the recordset
Data1.RecordSet.Delete
deletes the current record
Data1.RecordSet.MoveNext
moves to the next record in the recordset
Data1.RecordSet.MovePrevious
moves to the previous record
Data1.RecordSet.MoveFirst
moves to the first record
Data1.RecordSet.MoveLast
moves to the last record
Data1.UpdateRecord
saves a changed record. This is also done automatically when you use any of the
Move methods. With VB6, this is also done automatically when the control is
unloaded (when your application exits).

RecordSet Properties

Data1.RecordSet.EOF
True if MoveNext has moved us past the last record
Data1.RecordSet.BOF
True if MovePrevious has moved us in front of the first record
Data1.RecordSet.RecordCount
The number of records in the RecordSet. This is accurate with small RecordSets.
For large RecordSets you may have to perform a MoveLast to get this actual
value.
Data1.RecordSet.AbsolutePosition
The number of the current record in the RecordSet. Starts at zero. This property
does not appear to be reliable in VB6. I put code to display this in the Data
Control's Reposition event, and sometimes it worked, sometimes it gave odd
results.
Data1.RecordSet!fieldname
The contents of a specific field in the current record of the RecordSet. Replace
fieldname with the valid name of a field.
Yet Another (Bad) Way to Get Started: The Dataform Designer

Visual Basic 4 provided one other way to generate the beginning of a database
application: the Dataform Designer. It automatically creates a form, similar to what we
created with the first example, and includes some code for adding and deleting records.
However, you should plan to make some code modifications if you use this.

In Visual Basic 5, they've taken this component and put it in .... VisData. Yikes! Read on
to the last paragraph of this section before you spend a lot of time with this: the code
generated by Dataform Designer has serious flaws in both VB4 and VB5!

1. From the Add-Ins menu, choose Visual Data Manager again.


2. In Visual Data Manager, choose File/Open Database, and open a database file,
such as the one you created a few minutes ago.
3. In the Utility menu, choose DataForm Designer...
4. Fill in a name for your form at the top of the Dataform Designer dialog, and set
the RecordSource to a (the) table in your database.
5. Click the >> button to add all fields to this form.
6. Click on Build the Form. When it is done, Close the dialog.

If you set this form to be your startup form (in VB5, Project menu/Project
Properties/General/Startup Object), you can now run the program!

If you inspect the code, you will find that the Dataform Designer created event
procedures for clicking each of the five command buttons, plus procedures for the events
Data1_Error, Data1_Reposition, and Data1_Validate. Unfortunately, their code allows
the user to easily crash the program, and the Update button is very misleading. (Update
usually occurs whether you click it or not!). I recommend deleting the Refresh and
Update buttons, altering the code for the cmdAdd and cmdDelete click events, and
adding Form_Load and Form_Unload events. The recommended code is given a few
sections below.

Data Control Events: Error, Reposition, Validate

The Error event handles any error that occurs with the database. Use this event to code
what you want to happen when an error occurs.

The Reposition event occurs when the user moves to another record in the RecordSet.

The Validate event occurs prior to updates, either because of moving to another record or
explicitly asking for an update to occur. Use this event to do any validation on any of
your form fields prior to writing to the database. If a field is invalid, you can cancel the
update and the action that caused it by setting Action=0 and Save=False.
Basic Code for the Data Control

Although browsing and editing require no code, you must write code to add and delete
records. Furthermore, you should add a couple lines of code in your Form_Load event to
avoid an empty Recordset.

A problem that has plagued VB from the original database version is how it handles "no
current record". There are several situations where your "form" can be blank. It appears
to be an empty record or a record in which you can enter data, but it isn't! There's no
current record displayed. Information you type won't be saved, and trying a "delete" will
crash your program. It's important to avoid those situations.

Before VB6, when adding a record, if you didn't immediately UpdateRecord, the user
could crash the program by clicking Delete. They changed that in VB6. Now the program
doesn't crash.... instead you wind up deleting some other record!

Here is safe code for adding and deleting. The only issue you may have is if your
database has required fields. Before you use the UpdateRecord command, you should
assign default data to those fields. Otherwise, you must use an alternate method for
adding a new record.

The code below assumes you have Command Buttons for Add and Delete.

Private Sub cmdAdd_Click()


' Add a blank record and save it so it is the current record. It
gets put at the end.
Data1.RecordSet.AddNew
' Put code here if you have required fields in your database.
Assign default values.
Data1.UpdateRecord
Data1.Recordset.MoveLast
End Sub

Private Sub cmdDelete_Click()


Data1.RecordSet.Delete
' Now attempt to move forward to a valid record:
Data1.RecordSet.MoveNext
' But if we just deleted the Last record, we need to move back
instead:
If Data1.RecordSet.EOF Then
Data1.RecordSet.MovePrevious
' Now check to see if we've moved off the front...
' if so, we've just deleted the ONLY record! So add a new one...
If Data1.RecordSet.BOF Then
Data1.RecordSet.AddNew
Data1.UpdateRecord
Data1.Recordset.MoveLast
End If
End If
End Sub

Private Sub Form_Unload()


' add the following to Form_Unload to make sure any last changes
are saved:
Data1.UpdateRecord
End Sub

This "UpdateRecord" in the Form_Unload event may not be necessary in VB6. In earlier
versions it was needed, but the VB6 Data Control appears to automatically update the last
record when you exit the program.

If you have an Exit button, or a File menu with the Exit option (you should!), you should
use the line "Unload Me" to exit your program. In earlier programs it did not matter if we
used the other choice: "End". Now it does.

You might also like