How to read simple text files

Level:
Level1

Written By TheVBProgramer.
This tutorial describes how you can read text files in different formats and display them in your Visual Basic application. The samples here simply print the output to the main form, but this can easily be modified to do more advanced things with the text files.

$ReqTestHarness$

Since this tutorial uses a framework to test all the code in and sample text files it is probably easier to first Download the source code for it than follow along with the tutorial.

Visual Basic provides the capability of processing three types of files:

  • sequential files - Files that must be read in the same order in which they were written – one after the other with no skipping around
  • binary files - "unstructured" files which are read from or written to as series of bytes, where it is up to the programmer to specify the format of the file
  • random files - files which support "direct access" by record number

 

These three file types are "native" to Visual Basic and its predecessors (QBasic, GW-BASIC, etc.). The next several topics address VB's sequential file processing capabilities. Binary and Random files will be covered in later topics.

The following sequential file-related statements and functions will be discussed:

 

Open

Prepares a file to be processed by the VB program.

App.Path

Supplies the path of your application

FreeFile

Supplies a file number that is not already in use

Input #

Reads fields from a comma-delimited sequential file

Line Input #

Reads a line (up to the carriage return) from a sequential file

EOF

Tests for end-of-file

Write #

Writes fields to a sequential file in comma-delimited format

Print #

Writes a formatted line of output to a sequential file

Close #

Closes a file

 

As you know, a data file consists of records, which consist of fields. The file that will be used for all examples in this section is a simplified employee file, which consists of the following fields:

 

Field

Data Type

Employee Name

String

Department Number

Integer

Job Title

String

Hire Date

Date

Hourly Rate

Single

 

Suppose there were five records in the file. A graphic representation of the file populated with the five data records follows (the field names are not stored in the file):

 

Employee Name

Dept #

Job Title

Hire Date

Hourly Rate

ANDY ANDERSON

100

PROGRAMMER

3/4/1997

25.00

BILLY BABCOCK

110

SYSTEMS ANALYST

2/16/1996

33.50

CHARLIE CHEESEMAN

100

COMPUTER OPERATOR

3/1/1996

15.00

DARLENE DUNCAN

200

RECEPTIONIST

10/11/1998

12.75

ERNIE EACHUS

300

MAIL ROOM CLERK

8/19/1997

10.00

 

Please note that the data types for these fields are the data types of the variables into which these fields will be stored. On the sequential file, all fields will be represented as a string of characters.

 

Following are three different ways that the data in this sequential file might be stored; for example, if you opened up a sequential data file in a text editor such as Notepad, this is what you might see.

 

Scenario 1: Comma-Delimited Format

 

Each field is separated by a comma. Both string and numeric fields are "trimmed" (contain no extraneous spaces or zeroes). String fields are enclosed in quotes (Note: The quotes enclosing the string fields are optional, VB and other applications that can read comma-delimited files will access the string fields properly with or without the quotes. The only time a string field MUST be enclosed in quotes is when it contains an embedded comma.) If Date fields are enclosed in pound signs (#), VB will automatically recognize the field as the Date data type. If the Date fields are enclosed in quotes instead, you need to use the CDate function to convert the date from string format to the Date data type.

 

"ANDY ANDERSON",100,"PROGRAMMER",#3/4/1997#,25

"BILLY BABCOCK",110,"SYSTEMS ANALYST",#2/16/1996#,33.5

"CHARLIE CHEESEMAN",100,"COMPUTER OPERATOR",#3/1/1996#,15

"DARLENE DUNCAN",200,"RECEPTIONIST",#10/11/1998#,12.75

"ERNIE EACHUS",300,"MAIL ROOM CLERK",#8/19/1997#,10

 

Scenario 2: Fixed-Width ("Print" Format)

 

In some sequential data files, fields are stored in a fixed position. On each record, a particular field starts and ends in the same position and occupies the same amount of space. In a "print" format file, each line (record) of the file consists of a formatted "detail line" containing each field (as if the lines were intended to be printed on a hard-copy report).

 

In the example below, a column position guide is shown above the records. From the example, it should be clear that the employee name occupies positions 1 through 20 of each record (note that names shorter than 20 characters are padded with blank spaces); the department number occupies positions 21 through 24; the job title occupies positions 30 through 50; the hire date occupies positions 51 through 60; and the hourly rate occupies positions 61 through 65.

 

1 1 2 2 3 3 4 4 5 5 6 6

1...5....0....5....0....5...0....5....0....5....0....5....0....5.

ANDY ANDERSON 100 PROGRAMMER 3/4/1997 25.00

BILLY BABCOCK 110 SYSTEMS ANALYST 2/16/1996 33.50

CHARLIE CHEESEMAN 100 COMPUTER OPERATOR 3/1/1996 15.00

DARLENE DUNCAN 200 RECEPTIONIST 10/11/199812.75

ERNIE EACHUS 300 MAIL ROOM CLERK 8/19/1997 10.00

 

Scenario 3: Fixed-Width ("COBOL-Style" Format)

 

Typical of sequential files originating on mainframe computers and processed by languages such as COBOL, fields are stored one after the other in a continuous string with no distinguishing marks or white space between them. Although some of the character-string fields can be picked out easily, the numbers are run together and are difficult to interpret unless you know something about the record. Also, numeric fields containing a decimal portion are typically stored without the decimal point (they have an implied decimal point). For example, the employee file might look something like this:

 

1 1 2 2 3 3 4 4 5 5 6 6

1...5....0....5....0....5...0....5....0....5....0....5....0....5.

ANDY ANDERSON 0100PROGRAMMER 030419972500

BILLY BABCOCK 0110SYSTEMS ANALYST 021619963350

CHARLIE CHEESEMAN 0100COMPUTER OPERATOR030119961500

DARLENE DUNCAN 0200RECEPTIONIST 101119981275

ERNIE EACHUS 0300MAIL ROOM CLERK 081919971000

 

In the example above, the employee name occupies the first 20 positions of each record; the department number occupies the next four bytes (note that it contains a leading zero); the job title occupies the next 17 bytes; the hire date (stored in MMDDYYYY format with no slashes) occupies the next 10 bytes; and finally, the hourly rate occupies the last four bytes of the record. Note that the hourly rate does not contain a physical decimal point; however, the program that processes this file must "know" that the decimal point is implied (i.e., "2500" means "25.00"). Given the proper data definition, COBOL can interpret the implied decimal point just fine; in VB, we have to convert the string "2500" to a number and then divide it by 100. This technique is shown further below.

 

VB Statements and Functions for Sequential File Processing

 

The Open Statement

 

The Open statement prepares a file to be processed in the VB program. It identifies the Windows-system file that will be used in the program and assigns the file a file number that will be used to reference that file for the remainder of the program. The general format is:

Open <filename> [For mode] As [#] <filenumber>

 

·         filename is a legal Windows-system filename, which may include a drive and path; the filename can be specified in the Open statement as either a string constant or a string variable

 

·         mode is one of the following three keywords: Input, Output, or Append.

 

When a file is opened for Input, that file must already exist.

 

When a file is opened for Output, if it does not exist, it will be created; if it does exist, its previous contents will be overwritten.

 

When a file is opened for Append, if it does not exist, it will be created, if it does exist, records will be added to the file after the last record in the file (the previous contents of the file will not be overwritten).

 

The Input # and Line Input # statements may only be used on files opened in the Input mode; the Write # and Print # may only be used on files open in the Output or Append modes.

 

·         filenumber is an integer from 1 to 511 which is used to associate the Windows-system filename with a number; this number will be used to reference the opened file in all further VB file processing statements in the program.

 

Examples:

Open "C:\Program Files\EmpMaint\EMPLOYEE.DAT" For Input As #1

Open "A:\EMPLOYEE.DAT" For Input As #1

 

 

Using App.Path

 

In order to avoid "hard-coding" the path of a file in your VB program, it is recommended that you use App.Path to reference the path of the file. This way, as long as the file resides in the same directory in which your program is running, the correct path will always be referenced.

 

For example, if both your program and the data file reside in C:\Program Files\EmpMaint, then that is what App.Path would refer to. So if you concatenate App.Path with a backslash and the name of your data file, then you have a complete reference for your file, which can be used in the Open statement.

 

Examples:

Open App.Path & "\EMPLOYEE.DAT" For Input As #1

 

You could also use a string variable to hold the filename, as in the following example:

 

Dim strEmpFileName As String

strEmpFileName = App.Path & "\EMPLOYEE.DAT"

Open strEmpFileName For Input As #1

 

A special situation comes up if your program and the data file reside in the root directory of a drive (for example A:\). If you concatenate App.Path with a backslash and the filename, you'll come up with an invalid file reference, such as:

 

A:\\EMPLOYEE.DAT

 

To cover both situations and alleviate the pesky "extra backslash" problem, you can use code like the following (the new statements are shown in bold):

 

Dim strEmpFileName As String

Dim strBackSlash As String

strBackSlash = IIf (Right$(App.Path, 1) = "\", "", "\")

strEmpFileName = App.Path & strBackSlash & "EMPLOYEE.DAT"

Open strEmpFileName For Input As #1

 

 

Using FreeFile

 

Instead of hard-coding the file number, you can use the VB function FreeFile to supply you with a file number that is not already in use by the system. The FreeFile function takes no arguments and returns an integer. To use it, declare an integer variable, then assign FreeFile to it, as follows:

 

Dim intEmpFileNbr As Integer

intEmpFileNbr = FreeFile

 

In the Open statement (and any other statement that refers to this file), use the integer variable rather than the hard-coded number. For example:

 

Open strEmpFileName For Input As #intEmpFileNbr

 

Thus, a "full-blown" procedure to open a sequential file for input might look like this:

 

Dim strEmpFileName As String

Dim strBackSlash As String

Dim intEmpFileNbr As Integer

 

strBackSlash = IIf (Right$(App.Path, 1) = "\", "", "\")

strEmpFileName = App.Path & strBackSlash & "EMPLOYEE.DAT"

intEmpFileNbr = FreeFile

 

Open strEmpFileName For Input As #intEmpFileNbr

 

 

The Input # Statement

 

The Input # statement reads a series of fields (usually one "record's worth") from a comma-delimited sequential file, and stores the contents of those fields into the specified variables. The general format is:

 

Input #<filenumber>, <variable list>

 

·         filenumber refers to the file that was Opened As that number (for Input) in the Open statement

 

·         variable list is a list of variables, separated by commas, into which the data fields from the file will be stored

 

Example:

Recall the comma-delimited version of the employee file shown earlier:

 

"ANDY ANDERSON",100, "PROGRAMMER",#3/4/1997#,25

"BILLY BABCOCK",110,"SYSTEMS ANALYST",#2/16/1996#,33.5

"CHARLIE CHEESEMAN",100,"COMPUTER OPERATOR",#3/1/1996#,15

"DARLENE DUNCAN",200,"RECEPTIONIST",#10/11/1998#,12.75

"ERNIE EACHUS",300,"MAIL ROOM CLERK",#8/19/1997#,10

 

Assume you declare the following variables in your program:

Dim strEmpName As String

Dim intDeptNbr As Integer

Dim strJobTitle As String

Dim dtmHireDate As Date

Dim sngHrlyRate As Single

 

the statement

 

Input #intEmpFileNbr, strEmpName, intDeptNbr, strJobTitle, dtmHireDate, sngHrlyRate

 

would cause ANDY ANDERSON to be stored in strEmpName, 100 to be stored in intDeptNbr, PROGRAMMER to be stored in strJobTitle, 3/4/1997 to be stored in dtmHireDate, and 25 to be stored in sngHrlyRate the first time that the statement was executed. The second time the statement was executed, BILLY BABCOCK, 110, SYSTEMS ANALYST, 2/16/1996, and 33.5 would be stored respectively in strEmpName, intDeptNbr, strJobTitle, dtmHireDate, sngHrlyRate; and so on. As VB reads each field into its respective variable, it automatically performs the conversion to the correct data type (Integer, Date, Single, etc.). As mentioned earlier, VB will only convert an incoming field to the Date data type if that field is enclosed in pound signs (#) – if the field was enclosed in quotes, it would be treated as a string and the CDate function would have to be used to convert it to a Date.

 

VB "knows" that the data is to be read from the "EMPLOYEE.DAT" file because the Input # statement is referring to file #intEmpFileNbr, and file #intEmpFileNbr was associated with "EMPLOYEE.DAT" in the Open statement.

 

 

The EOF function

 

The operating system automatically appends a special character, called the end-of-file marker, to the end of a sequential file. VB can sense the presence of this end-of-file marker with the EOF function.

 

A programming language will generally recognize EOF at either one of two times: (1) after the last record has been read – OR – (2) at the same time that the last record has been read. COBOL falls into the first category, VB falls into the second.

 

FYI: This discussion applies only to how VB processes sequential files – because when VB processes the rows of a database table, it actually handles EOF "the COBOL way".

 

In a language that recognizes EOF after the last record in the file has been read (such as COBOL), the "input" or "read" loop is set up similar like a prompted dialog loop: with a priming read outside the loop; all subsequent reads occur at the bottom of the loop. The pseudocode might be written as follows:

 

READ (first) RECORD

DO UNTIL EOF

PROCESS THE RECORD

READ (next) RECORD

LOOP

 

In a language that recognizes EOF when the last record is read (such as VB), the "input" or "read" loop must be modified so that there is NO PRIMING READ and the read occurs as the FIRST statement in the body of the processing loop. The pseudocode might be written as follows:

 

DO UNTIL EOF

READ A RECORD

PROCESS THE RECORD

LOOP

 

The syntax of the EOF function is EOF(n) where n is a number corresponding to the file number of the file from which you want to read data. n can either be a hard-coded number or an integer variable, depending on whether or not you used FreeFile in the Open statement.

 

The EOF function can be used anywhere that a conditional expression can be used; as such, it must always follow keywords such as UNTIL, WHILE, and IF. The EOF function can also be preceded by the keyword NOT: for example, Do Until EOF(1) is equivalent to Do While Not EOF(1).

 

The main loop to process the employee file might look like this (note that there is no "priming" read and that the input is done at the top of the loop):

 

Do Until EOF(intEmpFileNbr)

Input #intEmpFileNbr, strEmpName, intDeptNbr, strJobTitle, dtmHireDate, sngHrlyRate

' Processing for the record would go here – for example, load some of these

' fields into an element of an array or list box, print a line of a report, etc...

Loop

 

Building on what has been discussed thus far, the "full-blown" procedure to process a comma-delimited sequential file for input might look like this:

 

Dim strEmpFileName As String

Dim strBackSlash As String

Dim intEmpFileNbr As Integer

 

Dim strEmpName As String

Dim intDeptNbr As Integer

Dim strJobTitle As String

Dim dtmHireDate As Date

Dim sngHrlyRate As Single

 

strBackSlash = IIf (Right$(App.Path, 1) = "\", "", "\")

strEmpFileName = App.Path & strBackSlash & "EMPLOYEE.DAT"

intEmpFileNbr = FreeFile

 

Open strEmpFileName For Input As #intEmpFileNbr

 

Do Until EOF(intEmpFileNbr)

Input #intEmpFileNbr, strEmpName, intDeptNbr, strJobTitle, dtmHireDate, sngHrlyRate

Print strEmpName; _

Tab(25); Format$(intDeptNbr, "@@@@"); _

Tab(35); strJobTitle; _

Tab(55); Format$(dtmHireDate, "mm/dd/yyyy"); _

Tab(70); Format$(Format$(sngHrlyRate, "Standard"), "@@@@@@@")

Loop

 

The Close statement

 

When you are finished using a file in your program, you should Close that file. The Close statement tells VB that you are done using a file, and frees up the system resources needed to process that file.

 

The statement

Close #1

frees the resources used by the file referenced as #1, and also terminates the association between the Windows-system file and the file number – so at this point, if you wanted to, you could Open some other file AS #1.

 

If you have more than one file open in a program, you can close multiple files with one Close statement by separating the file numbers with commas:

Close #1, #2, #68

 

The statement

Close

by itself on one line closes all files that are currently open.

 

In the "full-blown" example above, the following line should be added to the end (after the "Loop" statement):

 

Close #intEmpFileNbr

 

To demonstrate the code above

  • Create a new "Try It" project in a new folder. Make your form wide enough for the display.
  • In that same folder, create the comma-delimited file called EMPLOYEE.DAT (you can use NotePad for this)
  • Place the code in the cmdTryIt_Click event procedure.
  • Run the program and click the "Try It" button. The output should look like this:

 

 

 

Download the VB project code for the example above here.

 

If you enjoyed this post, subscribe for updates (it's free)

-

Type MyData
Header As string * 5
LB as Intiger
UB as Intiger
mydata () as string
end type
Const myheader = "Header"

As Binary <--
Public Function ReadMyFile(byval sFilename as Sting, h as Mydata) as Boolean
dim h as Mydata,f as intiger
if dir(sFilename)="" then ReadMyFile = False:exit function
f=freefile
open sFilename for binary access read as #f
get f,0, h
if h.header <> myheader then ReadMyFile = False : close f:exit function
redim h.mydata(h.LB to h.UB)
get f,0, h
close f
ReadMyFile=true
End function

'just a simple reading data file...long time not do this job....maybe not work....need fix??

Extract data from HTML to VB code

Hi, I have HTML table and need to filter the data in MSAccess. I'm using VB.
Can you plz advise best way to do it ?
Many thanks,
Abi

Find data from text file to display related data in listview

I have contain text as the following (path of file is "C:\Myfile.txt")
******R 0******
Name:Ana
TimeIn:10:12:20
TimeOut:12:25:00
******R 1******
Name:Bla
TimeIn:12:22:03
TimeOut:03:04:29
******R 3******
Name:Ana
TimeIn:01:50:23
TimeOut:05:10:22
******R 4******
Name:Cla
TimeIn:11:22:03
TimeOut:03:02:09
******R 5******
......
......
......
******R 15100******
Name:Ana
TimeIn:10:12:20
TimeOut:12:02:34

I have one TextBox, one Find Button when I type Ana on the TextBox =>Click Find Button it will collect data to display on ListView as below

Name TimeIn TimeOut
Ana 10:12:20 12:25:00
Ana 01:50:23 05:10:22
Ana 10:12:20 12:02:34

Please help to code with this

Many many thanks in advance.

I am ready to code it

Hello friend, I am ready to write code for your problem. If you want code mail me with details

extraction data from text.txt files

hi
i am visual Basic 6.0 bigger
i have text.txt file in different directories Now i facing for extraction data of such type

106615 70 21112 5 4 1
7963 239 21112 525 1
50215 1909 21112 536 1
8122 158 21112 545 1
7638 517 21112 554 1
3073 9 21112 555 1
104335 220 21112 650 1
7528 145 21112 830 1
71906 71 31112 535 1
108509 138 31112 537 1

Overflow

I have used the example as shown in the article, but I get the error code 6, overflow. I have no idea what that means or how to solve it. HELP!

Help

your array is to short try making it longer
try
Dim Thing(1000) as string
this gives you up to 1000 fields that can be saved

GOOD

Thakssssssss

during read of a textfile.how to select a last row of a text?

pls teach me how to make a command during read of a textfile.how to select a last row of a text? and also it is possible to have a automatic show of text in textbox.example i use barcode to another vb application then after barcode make a serial number in another vb application.it is possible that my vb application the serial number appear in another vb application also appear in my textbox???

How to read first and last word in textbox

Public Function GetFirstWord(ScanString As String) As String
Dim intPos As String
Dim intPosSave As String

If InStr(ScanString, " ") = 0 Then
GetFirstWord = ""
Exit Function
End If
intPos = 1
intPos = InStr(intPos, ScanString, " ")
GetFirstWord = Trim$(Left$(ScanString, intPos))
End Function
Public Function GetLastWord(ScanString As String) As String
Dim intPos As String
Dim intPosSave As String
If InStr(ScanString, " ") = 0 Then
GetFirstWord = ""
Exit Function
End If
intPos = 1
Do
intPos = InStr(intPos, ScanString, " ")
If intPos = 0 Then
Exit Do
Else
intPos = intPos + 1
intPosSave = intPos + 1
End If
Loop
GetFirstWord = Trim$(Mid$(ScanString, intPosSave + 1))
End Function

login page

Hi,

I am signing into my system either as a doctor or a nurse. How would i show that I have sign in as a doctor/nurse in the new form I entered.
I have already created a label to display the doctor/nurse. Anyway I am using a combo box in my login form for the option if doctor and nurse. Once logged in I cant retrieve the combo box text to my new form. Below are my codes.

Adodc1.RecordSource = "Select * from login where username = '" + Text1.Text + "'"
Adodc1.Refresh
If (Adodc1.Recordset.EOF = False) Then
If (Text2.Text = Adodc1.Recordset.Fields("password") And Combo1.Text = Adodc1.Recordset.Fields("Class")) Then
MsgBox "login Success"
Unload Me
MDIClinic.Show
MDIClinic.mnInvoice.Enabled = True
MDIClinic.mnConsultation_Treatment.Enabled = True
MDIClinic.mnPatient_Information.Enabled = True
MDIClinic.mnPatient_Registration.Enabled = True
MDIClinic.InvoiceButton.Enabled = True
MDIClinic.SSTab1.Enabled = True

MDIClinic.Label14.Caption = Combo1.Text < this is the line >tried debugging it

Else
MsgBox "invalid password"
Text1.Text = ""
Text2.Text = ""
Text1.SetFocus
End If
Else
MsgBox "invalid username"
Text1.Text = ""
Text2.Text = ""
Text1.SetFocus
End If

functions and reading data

Hello I was given this project to do over spring break. I don't know if I have read the data wrong or if my function is wrong can't seem to get the data to show up or the calculation to work. here what I am to do.
The data file is name P06.DAT, contains a Sales Person Name and a Sales amount in each of its data lines for every Sales Person of a company. Each data line has two data items as describe below:

Items # Description Data Type
1 salesperson name String (maximum length 16)
2 Sales Amount Floating-point

A salesperson is assigned commission on the flowing basis:

SALE AMOUNT COMMISSION
Less than $100 0.00 %
$100 to $999.99 2.85%
$1000 to $4999.99 4.75%
$5000 to $100000 6.95%
Over $10000 9.75%

At the top of your code you must provide a project name and Author Name
The Main() in the Module P06 will perform the as follows:
1. At the top of the output screen display Your name and Assignment #
2. Print Company Name and Column Headings.
3. Read each data line.
4. You use a Function to calculate Commission Amount, rounded to decimal places.
5. Compute running totals for Sales Amount, and Commission Amount.
6. Print Sales Person Name, Sales Amount, and Commission Amount under the heading.
7. At the bottom of the output print Total Sales Amount and Total Commission.

that is the assignment having trouble with the function I don't know if I have that wrong or the way I read and open the data file. Here is a copy of my program that I have so far wasn't sure how to round off to the 2 decimal and the floating- point I just am not good in the math area and how to do calculation. Any input would be grateful thanks.

'----------------------------------------------------------------------------'
' Project: P06VB '
' Author: Marie Albaugh '
'----------------------------------------------------------------------------'
Imports System.IO
Imports RahimLibrary

Module P06
Const AUTHOR As String = "Marie Albaugh Assignment 6"
Const HEAD1 As String = "MARIE ALBAUGH'S HEART OF GOLD"
Const HEAD2 As String = _
"SALESPERSON_NAME SALES_AMT COMMISSION"
Const LINE = _
"-------------------------------------------"
Const FMT As String = "0.00"
'-------------------- Subroutine: Main() -------------------------------------
Sub Main()
Dim Tokens As StringTokenizer
Dim Diskfile As String = "P06.DAT"
Dim separator As Char() = {" ", ",", ";", ":"}

Dim gap As Integer
Dim Name As String
Dim commission, totalSalesAmt, totalCommission, salesAmt As Decimal

totalSalesAmt = 0
totalCommission = 0

Console.WriteLine(AUTHOR & vbNewLine)
gap = (80 - HEAD1.Length) \ 2
Console.WriteLine(Space(gap) & HEAD1)
gap = (80 - HEAD2.Length) \ 2
Console.WriteLine(Space(gap) & HEAD2 & vbNewLine & Space(gap) & LINE)

If Not File.Exists(Diskfile) Then
Console.WriteLine("File: " & Diskfile & " does not exist")
Console.WriteLine(vbNewLine & vbNewLine)
Exit Sub
End If

FileOpen(1, Diskfile, OpenMode.Input)
While Not EOF(1)
Tokens = New StringTokenizer(LineInput(1), separator)

Name = Tokens.NextToken() & " " & Tokens.NextToken()
Name = Name & Space(16 - Name.Length)
salesAmt = Tokens.NextToken()
commission = Tokens.NextToken()
salesAmt = Tokens.NextToken()
commission = calculateCommission(salesAmt, commission)
totalSalesAmt = totalSalesAmt + salesAmt
totalCommission = totalCommission + commission

commission = salesAmt * commission

Console.WriteLine(Space(gap + 1) & Name _
& Format(Name, FMT).PadLeft(13) _
& Format(salesAmt, FMT).PadLeft(12) _
& Format(commission, FMT).PadLeft(13))
End While
FileClose(1)

totalCommission = salesAmt * commission
Console.WriteLine(Space(gap) & LINE & vbCrLf _
& Space(gap + 1) & "TOTALS:" _
& Format(totalSalesAmt, FMT).PadLeft(12) _
& Format(totalCommission, FMT).PadLeft(16) _
& vbCrLf & Space(gap) & LINE & vbCrLf & vbCrLf)

End Sub
'-------------------- Function: calculateCommission() -----------------------------
Function calculateCommission(ByVal salesAmt As Decimal, _
ByVal commission As Decimal) As Decimal

If (salesAmt > 100000) Then
commission = salesAmt * 9.55
ElseIf (salesAmt >= 5000) Then
commission = salesAmt * 6.95
ElseIf (salesAmt >= 1000) Then
commission = salesAmt * 4.75
ElseIf (salesAmt >= 100) Then
commission = salesAmt * 2.85
Else
commission = 0.0
End If
commission = Utility.Round(commission, 2)
'commission = Math.Round(commission,2)
'commission = Math.Floor(salesAmt * commission)

Return commission

End Function
End Module 'P06

The data file is this
Harry Hacker 75.79
Carl Cracker 99.99
Tony Teaser 100.00
Susan Shake 885.79
Barbara Bake 999.99
Carol Cook 1000.00
Shirley Stew 4575.79
Simple Pimple 4999.99
Horrible Huey 5000.00
Felix Laketrout 5759.53
Rickety Pork 10000.00
Peter Popcorn 10000.01
Quickdraw McGraw 12537.87

Thanks for your time

how to open text file with half of its name

Hi.

Can you help me,..?
How to open text file with half of its name using vb6. example i have 2 files in C:\,
they are :
1. Myfile10001.txt
2. Myfile20001.txt
I want to read file no.2 with 7 characters first (Myfile2xxxx.txt), and ignore next characters.

my script is :
Option Explicit
dim file1, file2, astrx
astrx = "*"
file1 ="c:\Myfile10001.txt"
file2 ="c:\Myfile2" & astrx & ".txt"

'this is run
Sub OpenTextFile1
Const ForReading = 1, ForWriting = 2, ForAppending = 3
Dim fs1, f1
Set fs1 = CreateObject("Scripting.FileSystemObject")
Set f1 = fs1.OpenTextFile(file1, ForReading,TristateFalse)
f1.Close
End Sub

'this is error
Sub OpenTextFile2
Const ForReading = 1, ForWriting = 2, ForAppending = 3
Dim fs2, f2
Set fs2 = CreateObject("Scripting.FileSystemObject")
Set f2 = fs2.OpenTextFile(file2, ForReading,TristateFalse)
f2.Close
End Sub

How to edit and arrange words in a text file?

Hi,

Can you please help me for this one, i'm confused on how to start my program. It's more like of a combination.

Here is what the original text file looks like:

"John dela Torre","14","Freshman","Math","English","Science","History","PE","C:\Johndelatorre.jpeg"
"Susan Green","13","Freshman","Math","English","Science","History","Home Economics","C:\Susangreen.jpeg"

And this is what the output should be

John dela Torre 14 Freshman Math
English
Science
History
PE C:\Johndelatorre.jpeg"

Im so confused with the split function and searching for the solution for rearranging this. Please help. T__T

Many Thanks

I would just like to say thank you to whoever writes these tutorials. I have made several attempts to learn VB but always seemed to get stuck trying to get my head around some of the context of the commands. I have read through all the tutorials so far and everything makes perfect sense now. As soon as I have read through them all I will go back and try the code with the confidence that I have some kind of idea as to what I am doing.
Great Work!!!!!
Many Thanks (again)
Tony

Excellent Tutorial..

How can I read from the middle(any place rather than the starting position) of a line in vb.

Use the Mid Function

To read from anyplace in your line, use the MID function. You have to know where you are starting (or you can use the INSTR function for this). Examples of both are shown below.

Dim intPosition as integer
Dim myString as string
Dim myOutput as string

myString = "Mary had a little lamb"
intPosition = instr(1,myString, "little") 'the 1 simply tells it from which character in the string (myString) to start looking.
myOutput = mid(myString, intPosition,6) ' this should return the word 'little'.

Alternative to APP.PATH

Its work done very well.

Just want to add the alternative way to APP.PATH
Instead of using (APP.PATH & "\") you can use ".\" it will always point to current working directory of VB6. i.e. the APP.PATH.

This method automatically gets rid of the double "\" problem.

You can also use "..\" to point to the parent directory of your APP.PATH.

Or ".\subdirectory" to point to a sub directory or sub-sub directory of App.Path

Superb.!!!!!!!!!

Really nice tutorial for beginners...!!!!!

how to open msoffice using vb

sir ,vb6.0 using sourcecode how to open msword,msexcel,notepad&msaccess in a single form to split the application display on single form

getting data to notepad

data received : 09276578797 8mins
data received : 09256578797 3mins
data received : 09276578797 8mins

i want to get all the number of 0927 to total the mins....
so the total minutes of 0927 is 16mins....

how can i make of this project... T_T

help me....

instr() is much better than using mid()

use instr(start,string_name_to_be_searched,string to find) and the full phone number can be found as many times as you like
also instr() will find " " for you so that you know where is the minutes info

getting data to notepad

do you have these data int he notepad or somewhere else on the form (like listbox)? either way, if you know how to read each entries int he notepad or list, you can use mid() function to see if the value is 0927 then use same mid() function to get the number of minutes and add it.

do you have these data int

do you have these data int he notepad or somewhere else on the form (like listbox)? either way, if you know how to read each entries int he notepad or list, you can use mid() function to see if the value is 0927 then use same mid() function to get the number of minutes and add it.

thankyou

thankyou

conversion

I want to know how can i convert the result of a program i made in gw basic in text form.
10 CLS
20 PRINT TAB(20) "list of names"
30 PRINT
35 A=0
40 PRINT TAB(20) "names"
50 PRINT
60 INPUT "enter your name|-",N$
65 PRINT LEFT$(N$,1),
70 A=A+1
80 IF LEFT$(N$,1)="z" THEN PRINT "end of the list":GOTO 130
90 GOTO 50
130 END

plz help me.....

So Cool ! Tut but how to

So Cool ! Tut

but how to make it "print" in textbox or listbox instead on a form

Please help me !

Random Access of Text Documents

hi! where can i find the tutorial for random access of files?
thanks...

Random Access of Text Documents

I'm too looking for this tutorial,
where to find it?

Cant write above 255 char in text File

Dim strFile                         As String
Dim strBackSlash                    As String
Dim strTextFileName                 As String
Dim strCurrentChar                  As String * 1
Dim intTextFileNbr                  As Integer
Dim lngX                            As Long
Dim rString                         As String
Dim wString                         As String
<code>
 
 
 
<code>Private Sub writeFile(strFile As String)
 
strFile = "MA.txt"
 
strBackSlash = IIf(Right$(App.Path, 1) = "\", "", "\")
'strTextFileName = App.Path & strBackSlash & "Test.txt"
    strTextFileName = App.Path & strBackSlash & strFile
 
 
     If Dir$(strTextFileName) <> "" Then
        Kill strTextFileName
    End If
 
' Open Output File
intTextFileNbr = FreeFile
    Open strTextFileName For Binary Access Write As #intTextFileNbr
 
      'For lngX = 1 To Len(wString)
   For lngX = 1 To 255
         strCurrentChar = Mid$(wString, lngX, 1)
         Put #intTextFileNbr, , strCurrentChar
    Next
  txtTemp.Text = Len(wString)
 Close #intTextFileNbr
a: 
End Sub<code>

wow

what an explanation to the code... Great man! Tons of thanks!

THANKS

THANKS

دانلود پروژه های دانشجویی

پروژه هایی که در این وب سایت ارائه می شوند در 5 گروه عمده به شرح ذیل می باشند:

پروژه های کارآفرینی

پروژه های تحت وب
2-1- پروژه های ASP.NET (وب سایتهای Dynamic)
2-2- پروژه های HTML (وب سایتهای Static)

پروژه های پایگاه داده
3-1- پروژه SQL Server
3-2- پروژه Access

پروژه های برنامه نویسی
4-1- برنامه نویسی به زبان سی شارپ (C#)
4-2- برنامه نویسی به زبان ویژوال بیسیک دات نت (VB.NET)
4-3- برنامه نویسی به زبان ویژوال بیسیک 6.0 (Visual Basic 6.0)
4-4- برنامه نویسی زبان ماشین (Assembly)
4-5- برنامه نویسی به زبان C و C++

پروژه های تجزیه و تحلیل سیستمها و مهندسی نرم افزار
5-1- تجزیه و تحلیل سیستمها به روش UML (متد RUP به همراه رسم نمودار با نرم افزار Rational Rose و . . . )
5-2- تجزیه و تحلیل سیستمها به روش SSADM (روش تحلیل شی گرایی و . . .)

پروژه های گرافیکی
6-1- پروژه های Multi Media Builder
6-2- پروژه های Flash MX

بیتاسافت مفتخر است که تاکنون با پشتیبانی 24 ساعته از مشتریان توانسته تا حدود زیادی رضایت مشتریان را جلب نماید. در همین راستا و برای جلب رضایت بیشتر مشتریان و برای پاسخگویی مناسبتر اقدام به ایجاد یک انجمن (Forum) نموده که دانشجویان و مشتریان محترم می توانند از این پس سوالات قبل از خرید ، در خواست آموزش و رفع ایرادات نرم افزاری خود را پس از خرید در این انجمن مطرح نمایند که در اسرع وقت توسط مسئول پشتیبانی به سوالات آنها پاسخ داده خواهد شد.
البته کماکان پشتیبانی از طریق تماس تلفنی و یا ارسال ایمیل و یا رفع اشکال حضوری در محل انجام پروژه ها بر قوت خود باقی خواهند ماند.
همچنین مشتریان و دانشجویان محترم می توانند قبل از خرید پروژه های موجود ، یک نسخه به صورت نمونه یا Demo از پروژه را مشاهده نمایند و در صورتی که پروژه مورد قبول واقع شد ، آن را خریداری نمایند.

تمامی پروژه های فوق الذکر دارای Document و مستندات ، پشتیبانی پس از فروش و آموزش در حد نحوه اجرا و استفاده از پروژه خریداری شده و گارانتی می باشد. در صورتی که به اطلاعات بیشتری نیازمندید با ما تماس حاصل فرمائید.

This is code is really

This is code is really helped me a lot to do my project...

Thank s...

Writing or editing textline

Hello, nice tutorial. Very useful

Can you also post writing or editing textline.

Thx in advance.

jterc

I like it

Graet lesson, very helpfull
Tanks

how do u get the app path to

how do u get the app path to work

wow..This is just amazing

wow..This is just amazing site and just wonderfukl article.

This is the best explanation one could ever give.u rcok man..

Thank you !

Very Nice explaination , much better than what i read in many books

thanks a lot sir

Wonderful Tutorial, just what we needed

Wonderful Tutorial, just what we needed..thxs

Great

Well done

how up load text files

how up load text files to sql server database by using vb6

how to open using a box like windows explorer

how do i allow the user to choose the file to open by using a open box like the one windows uses with windows explorer, e.g. in MS Word or Paint. I really need help!!!!!

Great tutorial =) it help me

Great tutorial =)
it help me so much tks [[]]

Very Nice Tutorial

One thing I really needed for our TLE Project.
I'm just a 15-year-old senior high school student and our teacher introduced VB6.0 to us and gave us so many activities and assignments that I can't catch up with the deadlines--I guess it's just too much for our age (but I think it's fun though, TLE is actually one of my favorite subjects)--so I sorely needed a tutorial for it.
Thank you so much! You don't know how much this helps me with our TLE projects and activities!

Very Nice Tutorial

One thing I really needed for our TLE Project.
I'm just a 15-year-old senior high school student and our teacher introduced VB6.0 to us and gave us so many activities and assignments that I can't catch up with the deadlines--I guess it's just too much for our age (but I think it's fun though, TLE is actually one of my favorite subjects)--so I sorely needed a tutorial for it.
Thank you so much! You don't know how much this helps me with our TLE projects and activities!

COOL

i always had problem with opening apps. at least now i can clearly open text or apps. tnx again

EXPORTING

CAN YOU TELL ME HOW TO EXPORT .FRM TO .EXE

Open the file in vb6 and go

Open the file in vb6 and go under file to export as project name.exe

Thanks

THANK YOU SO MUCH !!!
It is an outstanding effort from ur side, It was so helful for me.

God Bless U !!!!

If I only want to get a few

If I only want to get a few data from the text (not the whole text), how can I do it?

Quite helpfull but it does

Quite helpfull
but it does not show how to wirte into file

congrats, very good

congrats, very good 1

Márcio

vb6 textboxcontrol

can u tell me how can i bold or change the color of the selected text in the text box like in MS Word.

Wonderful Tutorial, just what we needed

Also, to read the text file line by line:

nHandle = FreeFile
 
Open "logfile.txt" For Input Access Read As #nHandle
 
Do While Not EOF(nHandle)   '// Loop until end of file.
 
  Line Input #nHandle, TextLine '// Read line into variable.
  ' use the TextLine herer...
 
Loop
Close #nHandle

Excellent Tutorial

A great piece of tutorial. Step by step and in a very simple way.
Keep it Up

Sameer
mauji90@yahoo.com

Exporting files

can you tell me ow to export files? for example, I created a loop that will record all the data into a variable. how can I export all the data in the variable into a text file?????

great

very very helpful

Scenario 2: Fixed-Width ("Print" Format)

i would like a tutorial that discribes how to read a text file with that format.

thanks, its a great tutorial.

ClaweD`s Answers :D

nice job :D
gonna post my own tutorials soon when i figure out how ^^

Great Wrok

I love this site,

great work

Thanks, very helpfull