2

So I'm pretty new to Visual Basic and inherited this VB6 code that i need to work on now. Right now, I'm trying to update a SQL database using an ADODB.RecordSet. I have a Select SQL statement that pulls the right data from the database into the ADODB.RecordSet, but I'm having problems updating all the rows. What I am trying to do is to update the same column for each row with the same value. Right now, its updating a few of the records, but I'm getting an error pop up. The error I get is:

Run Time error 3021: Either BOF or EOF is True or the current record has been deleted. Requested operation requires a current record.

When I click to debug, it takes me to rsUpdate.fields(TargetFieldName) = value

The project itself is huge and too large to post, but the part of the code that I'm working on now is this:

If rsUpdate.State = adStateOpen Then
  If rsUpdate.EOF Then
   rsUpdate.Close
   Exit Function
  End If
rsUpdate.MoveFirst
Dim i as Integer
For i = 0 To rsUpdate.recordCount
 rsUpdate.fields(TargetFieldName) = value
 rsUpdate.MoveNext
Next i
On Error GoTo canupdaterecord
rsUpdate.Update
On Error GoTo 0
rsUpdate.Close
End If
Exit function

So any help you guys can give me would be greatly appreciated. Like I said, I'm pretty new to VB and am kind of learning this all as I go.

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
gdawgrancid
  • 640
  • 3
  • 15
  • 37

2 Answers2

6

I would guess the problem is an off-by-one error:

For i = 0 To rsUpdate.recordCount
   rsUpdate.fields(TargetFieldName) = value       
   rsUpdate.MoveNext
Next i

If recordcount returns 5, this loop will make 6 runs: 0,1,2,3,4,5.

I'd write it like this:

while not rsUpdate.EOF do
   rsUpdate.fields(TargetFieldName) = value       
   rsUpdate.MoveNext
wend
Community
  • 1
  • 1
Anders Lindahl
  • 41,582
  • 9
  • 89
  • 93
0

Try this also:

If reUpdate.EOF Then 
    Exit Sub 
End If
shA.t
  • 16,580
  • 5
  • 54
  • 111
rekcah101
  • 27
  • 2
  • 10