Search code examples
vbams-accessfieldis-empty

Field in Access VBA code showing as Empty


I'm being tasked with altering a field "TimeAfterClass" (double) to produce a new field "NewTimeAfterClass" (also double) which would contain unique numbers. I created a button to accomplish this and it doesn't produce any errors but it also doesn't update the NewTimeAfterClass field and when I hover over [TimeAfterClass] it shows as Empty. Any suggestions as to why this is happening? Here is the code:

Private Sub Command0_Click()
Dim CurrentTimeAfterClass As Double
Dim NewTimeAfterClass As Double
Dim strSQL As String
Dim increment As Double
increment = 0.01
'Dim db As DAO.Database
Dim rs As ADODB.Recordset

'Set db = CurrentDb
Set rs = New ADODB.Recordset
With rs
    .Open "Scores", CurrentProject.Connection, adOpenDynamic, adLockBatchOptimistic
    .MoveFirst
    While Not .EOF
    CurrentTimeAfterClass = [TimeAfterClass]
    CurrentIncrement = 0
    CurrentIncrement = increment
        NewTimeAfterClass = CurrentTimeAfterClass + CurrentIncrement
            If CurrentIncrement > 0 Then
            CurrentIncrement = CurrentIncrement * (-1)
            Else
            CurrentIncrement = CurrentIncrement * (-1) + increment
            End If
    .Update
    .MoveNext
    Wend
End With

rs.Close
Set rs = Nothing
End Sub

Solution

  • Not sure what you're trying to do with increment, so I can only assume you know what you're doing.

    To make the Update work try this - maybe on a backup db??

    Private Sub Command0_Click()
        Dim CurrentTimeAfterClass As Double
    
        ' You don't need this if you're updating the field directly
        'Dim NewTimeAfterClass As Double
    
        Dim strSQL As String
        Dim increment As Double
        increment = 0.01
    
        'Dim db As DAO.Database
        Dim rs As ADODB.Recordset
    
        'Set db = CurrentDb
    
        Set rs = New ADODB.Recordset
        With rs
            .Open "Scores", CurrentProject.Connection, adOpenDynamic, adLockBatchOptimistic
            .MoveFirst
            While Not .EOF
            CurrentTimeAfterClass = !TimeAfterClass
            CurrentIncrement = 0
            CurrentIncrement = increment
    
            !NewTimeAfterClass = CurrentTimeAfterClass + CurrentIncrement
            If CurrentIncrement > 0 Then
                CurrentIncrement = CurrentIncrement * (-1)
            Else
                CurrentIncrement = CurrentIncrement * (-1) + increment
            End If
    
            .Update
            .MoveNext
            Wend
        End With
    
        rs.Close
        Set rs = Nothing
    End Sub