Question

This part of my program is designed to add user details to a random access file. The sub routine below is designed to do this:

    'This allows a user to be added to the User File
    Dim UserToAdd As User
    Dim UserFile As Integer
    Dim RecordNumber As Long

    'Read the data off the form and populate corresponding
    'UserToAdd values
    With UserToAdd
        .UserID = Val(txt_UserID.Text)
        .UserBarcode = txt_UserBarcode.Text
        .Forename = txt_Forename.Text
        .Surname = txt_Surname.Text
        .AccessRights = cmb_AccessRights.Text
    End With

    'Find the next open space in the User File
    UserFile = FreeFile()

    'Now open the file used to store User records
    FileOpen(UserFile, UserFileName, OpenMode.Random, OpenAccess.Write, OpenShare.Shared, Len(UserToAdd))
    RecordNumber = Len(UserFile) + 1

    'Add the new user to the file
    FilePut(UserFile, UserToAdd, RecordNumber)
    FileClose(UserFile)

There are no problems in actually saving the details, however, the file is overwritten every time another record is added. How could I stop this and what have I done wrong above?

Was it helpful?

Solution

It appears a couple things are happening, the first is since you are writing a RandomAccess file the Records need to be of the same length, therefore your Structure needs to be setup something like this (Since you didn't post your structure/class I am guessing that this could be a problem, if not the second issue is probably what is causing your issue).

Public Structure User
    Public UserId As Integer
    <VBFixedString(50)> Public UserBarCode As String
    <VBFixedString(20)> Public Forename As String
    <VBFixedString(20)> Public Surname As String
    <VBFixedString(20)> Public AccessRights As String
End Structure

The second is that your RecordNumber is not valid you are just getting the length of an Integer(your UserFile Variable). By giving your structure a fixed size you can use the LOF Method to get the length of your open file then divide that by your record size to determine the amount of records something like this.

RecordNumber = (LOF(UserFile) \ Len(UserToAdd)) + 1

As I said in my comment these functions are left over from VB6, but I can see why you would want to use them, there appears to be a lack of information on any other way.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top