07-13-2006, 05:01 AM
Reading and Writing to Text Files Using Microsoft Visual Basic 6
In Visual Basic, the ability to read and write to files can be a great value. You can use this to store High Scores for a game, or even write your own simple messaging system! The possibilites are endless. Just follow along with with tutorial and you will be reading and writing to files in no time.
Note: lines of code that are green are my comments. They explain what that section of coding does. They will not affect the code inside Visual Basic. Visual Basic will disregard any lines with a ' in front and show them as comments. Not run it with the coding.
The first step is to create your work folder. Keeping everything in one folder makes writing your code all that much easier. So create a folder, naming it whatever you want. Next open up Visual Basic 6 and create a new project, make sure to select "Standard EXE".
Our next step is to create the files we want to read and write to. Because we are using text files in this tutorial, inside the folder you created, create a new text file. Making the name simple will help to ensure a more organized program. I will name my text file "age.txt"
Lets assume at this point we are making a program that will record a persons age. So all we need is (2) text boxes, (2) labels, (3) command buttons, and (1) list box. So first lets gather all our necessary items. To add them to your form, just double click the icons in your toolbar to add them.
![[Image: vb_001.jpg]](http://www.erott.retect.com/resources/tutorials/vb/vb_001.jpg)
Next we will need to name them. For each of the objects, in the properties window, enter this information:
Label1
(Name): lblName
Caption: What is your name? //you will most likely have to make the label bigger
BackStyle: 0 - Transparent
TabIndex: 6
Label2
(Name): lblAge
Caption: What is your age? //you will most likely have to make the label bigger
BackStyle: 0 - Transparent
TabIndex: 7
Text1
(Name): txtName
Text: (delete the text inside of here to make the text box blank)
TabIndex: 0
Text2
(Name): txtAge
Text: (delete the text inside of here to make the text box blank)
TabIndex: 1
Command1
(Name): cmdSubmit
Caption: Submit
TabIndex: 2
Command2
(Name): cmdView
Caption: View
TabIndex: 3
Command3
(Name): cmdExit
Caption: Exit
TabIndex: 4
List1
(Name): lstView
Visible: False
TabIndex: 5
<--Before____After-->![[Image: vb_003.jpg]](http://www.erott.retect.com/resources/tutorials/vb/vb_003.jpg)
Now that we have our form created we can now begin to code it. First, double click on the "Submit" button; the one you created. A new window should pop open and you should see the section:
[quote[
Private Sub cmdSubmit_Click()
End Sub
[/quote]
That is the command buttons code section where everything we want the Submit button to do will go. Inside that section enter the following code so it will look like:
Next we must write the code that will allow us to read the contents of the text file. In addition, as a precaution, we are going to add a horizontal scroll bar to the list box in case the content is very long. So we will also have to be adding a module to our project. There is automatically a vertical scroll bar, so we do not need to add one. Double click on the View button you created and inside that section enter the following code so it would look like:
As for the module, will will have to first create one in our project. Under the Porject tab at the top of the page, click Add a Module. You can name the module whatever you like, it does not matter. Now, double click the module, and enter this code exactly:
Now we want to allow a user to safely exit the program. For this we use the Exit button. A simple word will end the program; that being "End". Double click the Exit button you created and enter this code so it will look like:
And that is all it takes to read from and write to text files using Visual Basic 6. Now that you've complete the tutotial yourself, if you are having trouble you can download the project from here. Or you can email me if you have any questions.
Author: Brendon LaRusic
Email: loosesniper@gmail.com
If you like this tutorial please register.
In Visual Basic, the ability to read and write to files can be a great value. You can use this to store High Scores for a game, or even write your own simple messaging system! The possibilites are endless. Just follow along with with tutorial and you will be reading and writing to files in no time.
Note: lines of code that are green are my comments. They explain what that section of coding does. They will not affect the code inside Visual Basic. Visual Basic will disregard any lines with a ' in front and show them as comments. Not run it with the coding.
The first step is to create your work folder. Keeping everything in one folder makes writing your code all that much easier. So create a folder, naming it whatever you want. Next open up Visual Basic 6 and create a new project, make sure to select "Standard EXE".
Our next step is to create the files we want to read and write to. Because we are using text files in this tutorial, inside the folder you created, create a new text file. Making the name simple will help to ensure a more organized program. I will name my text file "age.txt"
Lets assume at this point we are making a program that will record a persons age. So all we need is (2) text boxes, (2) labels, (3) command buttons, and (1) list box. So first lets gather all our necessary items. To add them to your form, just double click the icons in your toolbar to add them.
![[Image: vb_001.jpg]](http://www.erott.retect.com/resources/tutorials/vb/vb_001.jpg)
Next we will need to name them. For each of the objects, in the properties window, enter this information:
Label1
(Name): lblName
Caption: What is your name? //you will most likely have to make the label bigger
BackStyle: 0 - Transparent
TabIndex: 6
Label2
(Name): lblAge
Caption: What is your age? //you will most likely have to make the label bigger
BackStyle: 0 - Transparent
TabIndex: 7
Text1
(Name): txtName
Text: (delete the text inside of here to make the text box blank)
TabIndex: 0
Text2
(Name): txtAge
Text: (delete the text inside of here to make the text box blank)
TabIndex: 1
Command1
(Name): cmdSubmit
Caption: Submit
TabIndex: 2
Command2
(Name): cmdView
Caption: View
TabIndex: 3
Command3
(Name): cmdExit
Caption: Exit
TabIndex: 4
List1
(Name): lstView
Visible: False
TabIndex: 5
<--Before____After-->![[Image: vb_003.jpg]](http://www.erott.retect.com/resources/tutorials/vb/vb_003.jpg)
Now that we have our form created we can now begin to code it. First, double click on the "Submit" button; the one you created. A new window should pop open and you should see the section:
[quote[
Private Sub cmdSubmit_Click()
End Sub
[/quote]
That is the command buttons code section where everything we want the Submit button to do will go. Inside that section enter the following code so it will look like:
Quote:Private Sub cmdSubmit_Click()
Dim intMessageFile As Integer 'declare variable
Dim Age As String 'declare variable
Dim Name As String 'declare variable
Age = txtAge.Text 'give value to age variable
lstView.Visible = False
intMessageFile = FreeFile
Open "age.txt" For Append As #intMessageFile 'open the text file
Name = txtName.Text 'Give value to name variable
Write #intMessageFile, Name; Age 'write the name and age to age.txt
Close #intMessageFile 'close the text file
End Sub
Next we must write the code that will allow us to read the contents of the text file. In addition, as a precaution, we are going to add a horizontal scroll bar to the list box in case the content is very long. So we will also have to be adding a module to our project. There is automatically a vertical scroll bar, so we do not need to add one. Double click on the View button you created and inside that section enter the following code so it would look like:
Quote:Private Sub cmdView_Click()
lstView.Visible = True
Dim Content As String
Dim Message As String
intMessageFile = FreeFile
Open "age.txt" For Input As #intMessageFile
Do
If Not EOF(intMessageFile) Then
Input #intMessageFile, Message
Content = Message
lstMsgBox.AddItem Content
Else
Close #intMessageFile
'if you were not to include the below lines of code,
'Visual Basic would only read and display the first
'line of the text file. To overcome this, we tell the program
'to keep "looping"; reading everyline of the text file until it
'does not encounter anymore lines. Therefor reading and
'showing every line.
GoTo LoopEnd
End If
Loop
LoopEnd:
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
''''''''BEGIN ADDITION OF HORIZONTAL SCROLL BAR''''''''
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Dim c As Long
Dim rcText As RECT
Dim newWidth As Long
Dim itemWidth As Long
Dim sysScrollWidth As Long
'assure that the form font is the same as the
'list font to assure the DrawText method
'calculates the width correctly.
Form1.Font.Name = lstView.Font.Name
Form1.Font.Bold = lstView.Font.Bold
Form1.Font.Size = lstView.Font.Size
'get the width of the system scrollbar
sysScrollWidth = GetSystemMetrics(SM_CXVSCROLL)
'loop through the list items, using DrawText
'with DT_CALCRECT to determine the longest item.
For c = 0 To lstView.ListCount - 1
Call DrawText(Form1.hDC, (lstView.List©), -1&, rcText, DT_CALCRECT)
'calc the required width to display the
'widest list item by adding the rect
'width needed to display the item
'with the width of the system scroll bar
itemWidth = rcText.Right + sysScrollWidth
'if this width is wider than a previous
'value, save the longer width
If itemWidth >= newWidth Then
newWidth = itemWidth
End If
Next
'add a horizontal scrollbar wide enough
'to display the longest list item. If the
'scrollbar is not needed, its not shown.
Call SendMessage(lstView.hwnd, LB_SETHORIZONTALEXTENT, newWidth, ByVal 0&)
End Sub
As for the module, will will have to first create one in our project. Under the Porject tab at the top of the page, click Add a Module. You can name the module whatever you like, it does not matter. Now, double click the module, and enter this code exactly:
Quote:Public Const LB_GETHORIZONTALEXTENT = &H193
Public Const LB_SETHORIZONTALEXTENT = &H194
Public Const DT_CALCRECT = &H400
Public Const SM_CXVSCROLL = 2
Public Type RECT
Left As Long
Top As Long
Right As Long
Bottom As Long
End Type
Public Declare Function DrawText Lib "user32" _
Alias "DrawTextA" _
(ByVal hDC As Long, _
ByVal lpStr As String, _
ByVal nCount As Long, _
lpRect As RECT, ByVal _
wFormat As Long) As Long
Public Declare Function GetSystemMetrics Lib "user32" _
(ByVal nIndex As Long) As Long
Public Declare Function SendMessage Lib "user32" _
Alias "SendMessageA" _
(ByVal hwnd As Long, _
ByVal wMsg As Long, _
ByVal wParam As Long, _
lParam As Any) As Long
Now we want to allow a user to safely exit the program. For this we use the Exit button. A simple word will end the program; that being "End". Double click the Exit button you created and enter this code so it will look like:
Quote:Private Sub cmdExit_Click()
End
End Sub
And that is all it takes to read from and write to text files using Visual Basic 6. Now that you've complete the tutotial yourself, if you are having trouble you can download the project from here. Or you can email me if you have any questions.
Author: Brendon LaRusic
Email: loosesniper@gmail.com
If you like this tutorial please register.