Question

I'm creating a database for a local rental company. What I'm trying to do right now is create some code that can be periodically run to add bills to the database.

I have two tables I'm referencing here, the first is tblRental which is a table of rental units which includes rentalID's as a primary key, rental status, and the monthly rent, which is different on each unit. The other is tblTransaction which among other things includes the rentalID as a foreign key in a 1 to many relationship, and the amount for each bill which is named UnitRate. In the database rentalID and UnitRate are both set to numbers.

My code right now is

Dim maxRentalID As Integer

Dim db As Database
Dim rentID As DAO.Recordset
Dim unit As DAO.Recordset
Set db = CurrentDb
maxRentalID = Combo4.Value

For i = 1 To maxRentalID
    Set rentID = db.OpenRecordset("SELECT tblRental.RentalID, tblRental.Status FROM tblRental WHERE (((tblRental.Status)='3') AND ((tblRental.RentalID)=" & i & "));")
    Set unit = db.OpenRecordset("SELECT tblRental.Rentalcharge FROM tblRental WHERE (((tblRental.RentalID)=" & i & "));")
    If rentID Is Not Null Then
        DoCmd.RunSQL "INSERT INTO tblTransction ([RentalID], [UnitRate]) VALUES (" & rentID, unit & ");"
    End If
Next

maxRentalID is obtained from a form which determines the ID of the last record so that the for loop will go through until the end.

Right now I get a type mismatch error and it tells me the problem is with rentID in the DoCmd.RunSQL line.

I'm trying to make the loop run a query, and if it's a valid result (status=3 on a RentalID that exists), insert a new record into tblTransaction with that RentalID and corresponding billing rate.

Based on what the debugger says I assume that what's happening is the SQL isn't being evaluated into a statement with the query value being assigned to the variable and it's trying to put the statement into a number field which doesn't work. I'm not sure how to make it evaluate properly however. I've tried using OpenRecordSet for that but it doesn't work.

Was it helpful?

Solution

I would do it without loop and opening recordsets:

Dim maxRentalID As Integer
maxRentalID = Combo4.Value

CurrentDb.Execute "INSERT INTO [tblTransction] ([RentalID], [UnitRate]) " & _ 
                "SELECT [tblRental].[RentalID], [tblRental].[Rentalcharge] " & _ 
                "FROM [tblRental] " & _ 
                "WHERE [tblRental].[Status]='3' AND " & _ 
                      "[tblRental].[RentalID] BETWEEN 1 AND " & maxRentalID
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top