You are on page 1of 26

FileSystemObject in VBA – Explained inShare FileSystemObject also called as FSO, provides an easy object based model to access computer‟s

file system. You simply have to create an instance of FileSystemObject in VBA and then you can generate files, read files, delete files, iterate though foldersand do many other operations on your computer‟s file system. The FileSystemObject is present inside the Microsoft Scripting Runtime Library i.e. Scrrun.dll. This DLL supports the creation and manipulation of files using TextStream object and this is the reason why FSO doesn‟t supports operation on binary files. Uses of File System Object: FileSystemObject can be used for multiple tasks such as:

    

Creating, opening, reading, writing and deleting text files. Creating, altering and deleting folders. Iterating files and folders. Copying and moving files or folders. Checking if a location (file path) exists or not.

Accessing FileSystemObject: The FileSystemObject comprises of several object collections and each of these object collections contain information about a specific aspect of file system. These collections are: Object Description This object allows you to get information about a drive attached to your system. For instance it can tell you the space available in a drive, its logical name etc. Note that the drive object that we are referring here doesn’t necessarily means the hard disk, it can be a CD-ROM, Flash drive, RAM or even a logically connected drive via LAN. This object allows you to create, delete, move or query a folder hierarchy. This object allows you to create, delete, move or query a File. TextStream object allows you to read or write text files.


Folder File TextStream

So, diagrammatically a FileSystemObject can be shown as:

Please note that FSO communicates with most of the above objects indirectly. It just directly contains the object collection for “Drives”. Each “Drive” object in the “Drives” collection contains a chain of “Folder” objects. And each “Folder” object contains a “File” collection. To make it more meaningful, let‟s say it this way: A FileSystemObject contains three main methods to fetch (read) specific information about Drives, Folders or Files, these methods are GetDrive, GetFolder andGetFile respectively. Now let‟s say you need to find the file size of a particular file, so you will create an instance of the GetFile method and then fetch its size property. Note: GetDrive, GetFolder and GetFile are not the only methods inside FSO, I have just used them to explain things. In the below section we will see all the methods contained inside FileSystemObject. FSO Methods: Below table gives details about various FileObjectSystem methods and the tasks they perform:

Method GetDrive, GetFolder and GetFile CreateFolder and CreateTextFile DeleteFile and DeleteFolder

Description These methods are used for fetching information about Drive, Folders and Files respectively. Helps in creating new folders or files.

Helps in deleting exiting files or folders.

CopyFile and CopyFolder These methods help in copying files or folders from one location to another.  Next. MoveFile and MoveFolder Creating a FileSystemObject in VBA: In this section we will deal with two things:   Creating a reference of Microsoft Scripting Runtime Library i. navigate to “Tools” > “Reference” as shown above.dll Creating an FSO Object. These methods help in moving files or folders from one location to another. Creating a reference of Microsoft Scripting Runtime Library: To create a reference of Microsoft Scripting Runtime Library follow the below steps:  First of all open the VBA editor by pressing “Alt + F11”.e. Scrrun. .

. follow the below steps to do this:  In the VBA editor navigate to “Insert” > “Module”. Here select and chec k the entry “Microsoft Scripting Runtime” and click “OK”. Creating a FSO Object: Creating a FSO object is simple.  Now the reference to Microsoft Scripting Runtime Library has been added. This will open a references window.

Below is the code to do this: view plaincopy to clipboardprint? 1. If the folder doesn‟t exists then create that folder. Finally we have displayed the free space using a message box. MsgBox "Folder Exists!" . Space = Space / 1073741824 'converting bytes to GB 9. Example 2: Check if a Folder exists or not. MsgBox "C: has free space = " & Space & " GB" 11.FreeSpace anddrv. End Sub Explanation: In this code first we have created a Drive object using „GetDrive‟ Method and then we have used its „FreeSpace‟ property to fetch the free space. Note that there are two properties to fetch the free space of a drive i. Dim drv As Drive 5. 'Creating a FileSystemObject 2.  Now in the module window type “Public FSO As New FileSystemObject”.FolderExists(Fldr_name) = True Then 8. This will create an object of FileSystemObject with the name FSO.Round(Space.GetDrive("C:") ' Creating the the Drive object 7. Space = drv. 2) ' Rounding 10. Public FSO As New FileSystemObject 3. Public FSO As New FileSystemObject 3.e. Below is the code: view plaincopy to clipboardprint? 1. Fldr_name = InputBox("Enter the path of the folder to check :") 6. If FSO. Dim Fldr_name As String 5. After this you can simply access the FileSystemObject‟s methods using the FSO object. 'Creating a FileSystemObject 2. Space = WorksheetFunction. Sub DiskSpace() 4.FreeSpace 8. Set drv = FSO. Sub ChkFolder() 4.AvailableSpace. 6 Practical Examples of accessing FileSystemObject to perform different tasks: Now let‟s move to some practical examples of FSO: Example 1: Use FSO to find the total free space of a drive. Dim Space As Double 6. drv. If Len(Fldr_name) > 0 Then 7.

Dim Windows_Fldr As String . Else 10. FSO. Sub CopyFolder() 5. Example 4: Using FileSystemObject fetch the Temp directory. this method accepts three arguments:    Source Path Destination path A Boolean argument to specify Overwrite Existing. Example 3: Write a code using FSO to copy a Folder from one location to another.9. End Sub Explanation: In the code we have used an InputBox function to get the path of folder from the user. So.CreateFolder (Fldr_name) 11. To do this we can use the below code: view plaincopy to clipboardprint? 1. MsgBox "Copying Done!" 7. End If 13. 'Creating a FileSystemObject 2. System folder and Windows folder. If the folder is not present then we create that folder using the CreateFolder method. FSO. 'Creating a FileSystemObject 3. Sub GetFolderpath() 4.CopyFolder "C:\Source-Folder\". Note: CreateFolder method will only create a single folder at a time. if you supply an argument “C:\Folder1\Folder2\Folder3” to it then it will only create the Folder3 inside Folder2. True 6. But if Folder2 doesn‟t exist then it will throw a path not found error. view plaincopy to clipboardprint? 1. End Sub Explanation: In the code we have used the CopyFolder method of FSO. "D:\Destination-Folder\". Else 14. Public FSO As New FileSystemObject 4. MsgBox "Wrong Input" 15. Below is the code to accomplish this: 2. Public FSO As New FileSystemObject 3. End If 16. After this using If statement along with FolderExists method we have checked whether that folder is present or not. MsgBox ("Folder Created!") 12.

Dim System_Fldr As String 6.GetSpecialFolder(2) – Fetches the path of Local Temporary folder. 'Creating a FileSystemObject 2. this method accepts a single numerical argument i. Temp_Fldr = FSO. End Sub Explanation: In the code we have used the GetSpecialFolder method of FSO.    FSO.GetSpecialFolder(0) 8. Dim File As File 8.e. True) .txt" 'File to be created 9. Dim FileName As String 6. Dim txtstr As TextStream 5. Dim FileContent As String 7. Sub CreateFile() 4. "Temp folder path = " & Temp_Fldr) 13.5. System_Fldr = FSO. Example 5: Create a text file. True. Dim Temp_Fldr As String 7. Windows_Fldr = FSO. write some content to it. Public FSO As New FileSystemObject 3. "System folder path = " & System_Fldr & vbNewLine & _ 12.GetSpecialFolder(0) – Fetches the path of Windows Folder. 'Creating a file and writing content to it 10. FSO. Set txtstr = FSO.GetSpecialFolder(1) 9. If Len(FileContent) > 0 Then 12.GetSpecialFolder(1) – Fetches the path of System Folder. MsgBox ("Windows folder path = " & Windows_Fldr & vbNewLine & _ 11. 0-2.GetSpecialFolder(2) 10. FileName = "C:\TestDirectory\File. FileContent = InputBox("Enter the File Content") 11. Below is the code to accomplish this: view plaincopy to clipboardprint? 1. then read the file and finally delete the file.CreateTextFile(FileName. FSO.

Write FileContent 14. Set txtstr = File. "A").Count = 0 Then 15. Exit Sub 17.OpenAsTextStream(ForReading. Public FSO As New FileSystemObject 3. If FSO. and C 19. End If 25. then reads it. "B").Value = "Modified Date/Time" 22. ' Reading from the file that we have just created 17.Row + 1 24.Cells(Rows. TristateUseDefault) 20. 'Loop through each file in the folder . Cells(1.Count. B. Following code can accomplish this task: view plaincopy to clipboardprint? 1. txtstr. ' Finally Deleting the File 23. Set objFolder = FSO. txtstr. 'Creating a FileSystemObject 2.13. End Sub Explanation: This code first creates a text file. Set File = FSO. 'Check if the folder is empty or not 14. MsgBox txtstr.. Dim objFile As File 7.. strPath = "C:\Users\Aniee\Desktop\ExcelTrick\ " 11. NextRow = ActiveSheet.". 'Create the object of this folder 12.Value = "Size" 21.ReadAll 21. 'Adding Column names for A. 'Find the next available row 23. displays it using a message box and finally deletes that file.FileExists(FileName) Then 18. Cells(1. File. txtstr.GetFolder(strPath) 13.End(xlUp). Cells(1. Example 6: Write a VBA Code that can iterate all the files present inside a folder and also fetches their size and modified date. 'Declaring variables 5. vbExclamation 16.GetFile(FileName) 19.Files. Dim objFolder As Folder 6. "C"). MsgBox "No files were found.Value = "File Name" 20.Delete (True) 24. End If 18. Dim strPath As String 8. Sub ListFiles() 4. End If 16.Close 15. adds content to it. "A").Close 22. If objFolder. 'Specify the path of the folder 10. Dim NextRow As Long 9.

size. For Each objFile In objFolder. Do share your comments related to the topic. 2). this was all about FileSystemObject and how to use it in VBA. Next objFile 33. 'Find the next row 31.25.Value = objFile. 'List the name."References" from the menu bar. Size and DateLastModified properties and finally we are writing them to the active worksheet. you have to add the "Microsoft Scripting Runtime Library" to the current project by selecting "Project". Cells(NextRow. From the file object we are fetching the Name. folders and drives as well as read and write to sequential files.Files 26. End Sub Explanation: In this code we have created a Folder object and then we are iterating all its files using For Each loop. NextRow = NextRow + 1 32. Alternatively you can use the CreateObject function to create the reference at run-time. Cells(NextRow.DateLastModified 30. 3). and date/time of the current file 27. So.Value = objFile. Before using the FSO. Set fso = CreateObject("Scripting. File Handling And FSO Object Tips >> Visual Basic The File System Object (FSO) enables you to manipulate the files.Size 29.FileSystemObject") EXAMPLE PROGRAMS: The following example programs illustrate how to use the File System Object. . 1). Cells(NextRow.Value = objFile.Name 28.

The following is a list of some of the methods avaiable to the FileSystemObject. Used to copy an existing folder. . The FileSystemObject is used to manipulate the files. Used to delete a folder. Used to determine whether a drive exists. Used to determine whether a file exists. Random Access Files. Used to create a folder. Folder. File. 3. Drive.Listing Setting subdirectories Recursively Attributes Loading subdirectories into the TreeView control FILE SYSTEM OBJECT: There 1. File System Object Methods Method CopyFile CopyFolder CreateFolder CreateTextFile DeleteFile DeleteFolder DriveExists FileExists Description Used to copy an existing file. 4. Used to create a text file. Used to delete a file. 5. TextStream. 2. folders and directories. are five types of File System Object.

GetAbsolutePathName Used to return the full path name. GetParentFolderName Used to return the name of the parent folder. Used to return a specified file. Used to move a file.Name & vbCrLf strInfo = strInfo & "Created: " . Used to move a folder. Private Sub displayFileInfo(ByVal fileName As String) Dim fso As New FileSystemObject Dim fileSpec As File Dim strInfo As String Set fileSpec = fso.FolderExists Used to determine whether a folder exists. GetTempName MoveFile MoveFolder OpenTextFile Used to create and return a string representing a file name. GetDrive GetDriveName GetFile GetFileName GetFolder Used to return a specified drive. Used to return the file name. The FSO File Object The following uses some of the FSO File's properties to display information about a file. Used to open an existing text file. Used to return a specified folder. Used to return the drive name.GetFile(fileName) strInfo = fileSpec.

vbInformation.Name & vbCrLf strInfo = strInfo & "Created: " strInfo = strInfo & folderSpec. and Move methods are available for the FSO Folder object. "Folder Information" Set folderSpec = Nothing End Sub The Copy. . vbInformation.Size MsgBox strInfo.GetFolder(folderName) strInfo = folderSpec. CreateTextFile.DateCreated & vbCrLf strInfo = strInfo & "Size: " strInfo = strInfo & folderSpec. "File Information" Set fileSpec = Nothing End Sub The Copy. Private Sub displayFolderInfo(ByVal folderName As String) Dim fso As New FileSystemObject Dim folderSpec As Folder Dim strInfo As String Set folderSpec = fso.DateLastAccessed & vbCrLf strInfo = strInfo & "Last Modified: " strInfo = strInfo & fileSpec.DateLastModified MsgBox strInfo. and openAsTextStream methods are available for the FSO File object.DateCreated & vbCrLf strInfo = strInfo & "Last Accessed: " strInfo = strInfo & fileSpec. Delete. Delete. The FSO Folder Object The following uses some of the FSO Folder's properties to display information about a folder. Move.strInfo = strInfo & fileSpec.

THE FSO DRIVE OBJECT The following example iterates through the Drives collection and writes the drive name for each drive found. Dim fso As New FileSystemObject Dim connectedDrives As drives.ShareName Else driveName = drv.drives On Error Resume Next For Each drv In connectedDrives strInfo = strInfo & drv. drv As Drive Dim strInfo As String.FreeSpace If drv.VolumeName End If strInfo = strInfo & driveName strInfo = strInfo & " Free space: " & drv.DriveType = 3 Then driveName = drv. vbInformation.DriveLetter & ": " ' Check if the drive is shared If drv. . "Connected Drives" Set connectedDrives = Nothing Set fso = Nothing The FSO TextStream Object The FSO TextStream object is used to read and write to sequential text files. driveName As String Set connectedDrives = fso.IsReady Then strInfo = strInfo & " ready" & vbCrLf Else strInfo = strInfo & " not ready" & vbCrLf End If Next drv MsgBox strInfo.

you can either create a new file. The default value is True.txt". The CreateTextFile method takes as parameters the filename to be created and a Boolean value indicating whether the file should be overwritten if it exists. overwrite an existing file or append text to the end of an existing file. The CreateTextFile method is used to create a text file and return a reference to a TextStream object. True) ' Write to the file fsoStream. and return a reference to a TextStream Set fsoStream = fso. ForReading or ForWriting. the WriteBlankLine method is used to write blank lines and the WriteLine method is used to write a line of text ending with a newline character.WriteBlankLines 2 fsoStream. The Write method is used to write a string.WRITING TEXT FILES When writing to a file. Dim fso As New FileSystemObject Dim fsoStream As TextStream ' Create a text file." fsoStream.WriteBlankLines 2 fsoStream.WriteLine "First line in the text file." The FSO TextStream CreateTextFile Method The following example creates a text file using the CreateTextFile method. fsoStream.Write "Hello" fsoStream." fsoStream.WriteLine "First line in the text file.WriteLine "Line after two blank lines.Close Set fsoStream = Nothing . The FSO File object'sOpenAsTextStream method may be used to open a TextStream ForAppending.CreateTextFile("c:\junk\junk.

Close Set fsoStream = Nothing Set fso = Nothing READING TEXT FILES The FSO File object's OpenAsTextFile(ForReading) is used to open a text file for reading. The Read. Text written to the file is appended to the end. ReadAll and ReadLinemethods are used to read from the text file. . Dim fso As New FileSystemObject Dim f As File Dim fsoStream As TextStream Set f = fso. The Read method takes as a parameter the number of characters to be read.WriteLine "Appending line to the text file" fsoStream.txt") Set fsoStream = f. open the TextStream using the ForAppending parameter.GetFile("c:\junk\junk. This is not advisable for large files as it's a waste of memory.Set fso = Nothing APPENDING TO THE END OF A TEXTSTREAM To append to a file. The ReadAll method reads the whole text file.OpenAsTextStream(ForAppending) ' Append lines to the file fsoStream.

and the AtEndOfLine property may be used to for the end of a line.txt") Set fsoStream = f.ReadAll lineText = fsoStream.The ReadLine method reads one line of text from the file. READING EXAMPLE: To read a file.Print strLine Loop fsoStream. The AtEndOfStream property may be used to test for the end of file. Dim fso As New FileSystemObject Dim f As File Dim fsoStream As TextStream Dim strLine As String Set f = fso.Read(1) wholeFile = fsoStream.ReadLine The Skip(n) method may be used to skip n characters. and the SkipLine method is used to skip a whole line.ReadLine Debug. printing the results to the Form Do While Not fsoStream. open the TextStream using the ForReading parameter.OpenAsTextStream(ForReading) ' Read the file line by line.AtEndOfStream strLine = fsoStream.GetFile("c:\junk\junk.Close Set fsoStream = Nothing Set f = Nothing Set fso = Nothing . singleChar = fsoStream.

##0") txtDisplay.Text & vbCrLf & strSummary Else txtDisplay.Size.Path) > 3 Then txtDisplay. strSummary As String strStart = dirFiles.Example Programs The following examples all use the FSO Object. The number of directories found and the total size is written as a summary at the end. startFolder As Folder Dim numFolders As Integer Dim strStart As String.Text = "" Set startFolder = fso.     Listing subdirectories Recursively Setting Attributes Loading subdirectories into the TreeView control List subdirectories recursively The following example iterates through directories recursively writing the name to a MultiLine TextBox. Option Explicit Private Sub dirFiles_Change() Dim fso As New FileSystemObject.Text = txtDisplay.Path ' Avoid root directories as it's likely to run out of memory If Len(dirFiles. True) strSummary = numFolders & " Folders.Text = "" End If Set startFolder = Nothing Set fso = Nothing End Sub Private Function displayFolder(ByVal folderName As . " strSummary = strSummary & "Total size: " & Format(startFolder. "#.GetFolder(strStart) numFolders = displayFolder(strStart.

Text & rootFolder & vbCrLf folderCount = folderCount + 1 For Each currentFolder In rootFolder. ByVal firstTime As Boolean) As Integer Dim fso As New FileSystemObject Dim rootFolder As Folder.String.1 Set f = fso.Path & "\" & filList.SubFolders txtDisplay.Text = txtDisplay. subFolder As Folder Static folderCount As Integer Set rootFolder = fso. True) Next subFolder Next currentFolder displayFolder = folderCount Set rootFolder = Nothing Set fso = Nothing End Function SETTING ATTRIBUTES: The following example sets the file attributes for all files meeting a specified file pattern in a directory.Text & currentFolder & vbCrLf folderCount = folderCount + 1 For Each subFolder In currentFolder.SubFolders folderCount = folderCount + displayFolder(subFolder.GetFolder(folderName) If firstTime = True Then folderCount = 0 End If txtDisplay.ListCount .Path. currentFolder As Folder. Option Explicit Private Sub cmdAttributes_Click() Dim fso As New FileSystemObject Dim f As File Dim counter As Integer.GetFile(filList.Text = txtDisplay. attValue As Integer For counter = 0 To filList.List(counter)) attValue = 0 .

Attributes = attValue Next counter End Sub Private Sub dirList_Change() filList.Text End If End Sub .If chkAttributes(0). description.Path = drvDrive.Path End Sub Private Sub drvDrive_Change() On Error GoTo driveError retryDrive: dirList.Text) End Sub Private Sub txtPattern_KeyPress(KeyAscii As Integer) If KeyAscii = 13 Then KeyAscii = 0 filList.Pattern = txtPattern.Value = 1 Then attValue = 32 End If If chkAttributes(1). "Drive Error") If response = vbRetry Then Resume retryDrive End If End Sub Private Sub txtPattern_GotFocus() txtPattern.SelStart = 0 txtPattern.Drive Exit Sub driveError: Dim response As Integer.description.Value = 1 Then attValue = 1 End If If chkAttributes(2). description As Integer description = vbExclamation + vbRetryCancel response = MsgBox(Err.SelLength = Len(txtPattern.Value = 1 Then attValue = 2 End If f.Path = dirList.

currentFolder As Folder.Image = "open" End Sub Private Sub addFolder(ByVal folderName As String) Dim fso As New FileSystemObject Dim rootFolder As Folder.Node) Node. Option Explicit Private Sub cmdSelect_Click() Dim x As Node txtSelection.Text = txtSelection.Nodes If x. When the "Select Files" CommandButton is clicked.Key & vbCrLf End If Next x End Sub Private Sub Form_Activate() Dim fso As New FileSystemObject.Checked Then txtSelection.Node) Node. startFolder As Folder.Checkboxes = True Set startFolder = fso. subFolder As Folder Dim strParentName As String . subFolder As Folder tvwFileSystem.SubFolders addFolder CStr(subFolder) Next subFolder End Sub Private Sub tvwFileSystem_Collapse(ByVal Node As MSComctlLib.Loading subdirectories into the TreeView control The following example lists all of the directories in the C Drive in a TreeView control.Text & x.ImageList = imlImages tvwFileSystem.Image = "closed" End Sub Private Sub tvwFileSystem_Expand(ByVal Node As MSComctlLib.Text = "" For Each x In tvwFileSystem. the nodes with a check in them are added to the Selection TextBox.GetFolder("C:\") For Each subFolder In startFolder.

Add CStr(rootFolder).Name. Data may be inserted into the file without destroying any other data in the file. .Name.ParentFolder If Len(strParentName) > 3 Then tvwFileSystem. tvwNext. tvwChild. "closed" End If End If For Each currentFolder In rootFolder.Set rootFolder = fso. rootFolder. rootFolder. USER DEFINED TYPES: A user defined type is a collection of variables that create a new type. currentFolder. They are commonly used to define fixed length records that may be used in random access files. The following is an example of a user defined type in Visual Basic.Add . which is the case with sequential files. rootFolder. closed" Else tvwFileSystem.SubFolders addFolder subFolder.Nodes.Nodes. currentFolder.IsRootFolder Then strParentName = rootFolder. "closed" For Each subFolder In currentFolder. tvwChild. which may be thought of as a record.Name.SubFolders tvwFileSystem.Add strParentName.Nodes.GetFolder(folderName) If Not rootFolder. Data may also be amended or deleted without having to rewrite the entire file. rootFolder.Path Next subFolder Next currentFolder End Sub RANDOM ACCESS FILES: Visual Basic uses fixed length records in order to implement random access files.

OPENING RANDOM ACCESS FILES: Random access files may be opened as "read only". Open filename For Random Access Read Write As #1 Len = recordLength The As clause specifies a file number that will be used as a handle to reference the file. The FreeFile can be used to get the next free file number. the default is read and write.Private Type clientRecord accountNumber As Integer strSurname As String * 15 strForename As String * 15 balance As Currency End Type The variables declared within the type are members of the type.accountNumber = 100 Debug.Net. String variables are given a fixed length in order that the record is a fixed length. Members of the record are accessed using the dot operator as in the following example.accountNumber Note: Fixed length strings are not supported in VB. . "write only" or "read and write". If no mode is specified.Print cr. Dim cr As clientRecord cr.

and the user defined type. Get #1. The following example write the data stored in the user defined type to record 4 from file handle 1. and the user defined record. The following example gets record 8 from file handle 1 and places it in a user defined record. The Get function takes as parameters the file handle.Dim fileNum As Integer fileNum = FreeFile Open filename For Random As #fileNum Len = recordLength Reading and Writing to Random Access Files Get is used to read a record a record from a text file into a user defined record. Put #1. 8. 4. userRecord . the record number. userRecord The Put function takes as parameters the file handle. and Put is used to write a user defined record to a file. the record number.

FileTitle = "" ' Open the file for read and write Open strFilename For Random Access Read Write As #1 Len = recordLength Get #1.CancelError = True ' Get a valid filename Do cdlOpen. If the file does not exist. 1. 100 blank records are written to the file.accountNumber = 0 Then initialiseFile End If populateFields 1 Exit Sub userCancelled: ' The user chose to cancel. Option Explicit Private Type clientRecord accountNumber As Integer strSurname As String * 15 strForename As String * 15 balance As Currency End Type Private Sub Form_Activate() Dim strFilename As String Dim recordLength As Long Dim cr As clientRecord recordLength = LenB(cr) On Error GoTo userCancelled cdlOpen. so end the program End End Sub Private Sub cmdFirst_Click() updateRecord populateFields 1 .RANDOM ACCESS FILE EXAMPLE The following example uses a user-defined type for a random access file. cr If cr.ShowOpen strFilename = cdlOpen.filename Loop While cdlOpen.

blankRecord . vbInformation. "Exit Program") If response = vbNo Then Cancel = True Else updateRecord Close #1 End If End Sub Private Sub initialiseFile() Dim counter As Integer Dim blankRecord As clientRecord ' write 100 blank records to the file For counter = 1 To 100 blankRecord.Caption) > 1 Then updateRecord populateFields Val(lblAccountNumber.Caption + 1) Else MsgBox "At last record".1) Else MsgBox "At first record". "Random Access Files" End If End Sub Private Sub Form_Unload(Cancel As Integer) Dim response As Integer response = MsgBox("Are you sure". vbQuestion + vbYesNo.End Sub Private Sub cmdLast_Click() updateRecord populateFields 100 End Sub Private Sub cmdNext_Click() If Val(lblAccountNumber.Caption .accountNumber = counter Put #1. vbInformation.Caption) < 100 Then updateRecord populateFields Val(lblAccountNumber. "Random Access Files" End If End Sub Private Sub cmdPrevious_Click() If Val(lblAccountNumber. counter.

balance = Val(txtBalance. "Random Access Files" End Sub Private Sub populateFields(ByVal recNo As Integer) Dim cr As clientRecord Get #1.Text = cr.SelStart = 0 txtBalance.Caption) cr.SelLength = Len(Trim(txtBalance.accountNumber = Val(lblAccountNumber.Caption = cr. recNo.SelStart = 0 txtSurname. vbInformation. cr lblAccountNumber.strForename txtSurname.accountNumber txtForename.Text) Put #1.strForename = txtForename.Caption).Text)) End Sub Private Sub txtForename_GotFocus() txtForename.Text)) End Sub Private Sub txtSurname_GotFocus() txtSurname. cr End Sub Private Sub txtBalance_GotFocus() txtBalance.Text)) End Sub .Text = cr.strSurname = txtSurname.SetFocus End Sub Private Sub updateRecord() Dim cr As clientRecord cr.SelLength = Len(Trim(txtSurname.balance txtForename.SelLength = Len(Trim(txtForename.Text cr.SelStart = 0 txtForename.Text = cr.Text cr.strSurname txtBalance.Next counter MsgBox "File initialised". Val(lblAccountNumber.