Anda di halaman 1dari 2

Writing to a file sequentially

txtName txtRegion txtAmount

cmdPrintToForm cmdAddToFile cmdSearch lblMessage

lstDisplay

Public Sub Form_Load() Form1.BackColor = RGB(0, 0, 255) 'Gives colour to form End Sub Adds the data inserted in the text boxes in the text file called Sales defines data type, assigns the variables with the content of text boxes if the variables are empty then displays message in the gray shaded box else opens file, places pointer at the end and writes the data once they have been written we clear the text boxes Private Sub cmdAddToFile_Click() Dim Name As String Dim Region As String Dim Amount As String Dim FileName As String FileName = App.Path & "\Sales.txt" Name = txtName.Text Region = txtRegion.Text Amount = txtAmount.Text If (Name = "" Or Region = "" Or Amount = "") Then lblMessage.Caption = "MISSING DETAILS." Else Open FileName For Append As #1 Write #1, Name, Region, Amount 'Write puts quotes and separates with commas Close #1 txtName = "" txtRegion = "" txtAmount = "" txtName.SetFocus End If End Sub

Displaying data from text file sequentially


Open the file for input/display its content, before writing each line we clear the list until it reaches the End Of File it will read line by line from the top to the end and input the data into a variable called DisplayData which will then be added to the list area. Private Sub cmdPrintToForm_Click() Dim DisplayData As String Dim FileName As String FileName = App.Path & "\Sales.txt" Open FileName For Input As #1 lstDisplay.Clear Do While Not EOF(1) Line Input #1, DisplayData lstDisplay.AddItem DisplayData Loop Close #1 End Sub

Searching a text file sequentially


Assign Data types to variables, the search criteria will be the data input in the name text box. It checks the length of the variable we are searching so that its not empty. Opens the file for reading where the length of the data matches (case sensitive) if it finds it then writes the equivalent region and amount found on the same line, else prints error message that nothing was found. Finds first instance of name and stops Private Sub cmdSearch_Click() Dim DisplayData, searchName, FileName As String Dim Name, Region, Amount As String Dim Found As Boolean Dim NumberOfRecords As Integer FileName = App.Path & "\Sales.txt" Found = False NumberOfRecords = 0 searchName = txtName.Text If Len(searchName) = 0 Then lblMessage.Caption = "MUST TYPE IN SEARCH BOX." Else Open FileName For Input As #1 Len = Len(searchName) Do While (Not EOF(1)) And (Found = False) Input #1, Name, Region, Amount If searchName = Name Then Found = True txtName = Name txtRegion = Region txtAmount = Amount Else lblMessage.Caption = "NO MATCHES FOUND." txtName = "" txtRegion = "" txtAmount = "" End If Loop Close #1 End If End Sub

Anda mungkin juga menyukai