访问VBA将表值比较为常量并更新它

时间:2013-01-11 21:26:08

标签: database vba compare

好的,所以我正在尝试编写VBA代码以尽可能自动化。我需要它做的是从表中的字段读取它是否满足条件而不是将其复制到新表。这是为了轮换目的。如果CurrentDate等于NextDateOut,那么我想要转到某个表但又想要更新当前表中的值的任何值。 NextDateOut将是表格中的新LastDateOut值,而NextDateIn将是距离NextDateIn 10天,NextDateOut将是10天后。我可以编写这个数学逻辑,只是将我的表格中的值与我的常量值CurrentDate进行比较,并在条件满足时更新值并将值写入某个表格。

到目前为止,这是代码,并且还有很多错误试图解决它。

Option Explicit
Sub Run()
    'Declarations for grabbing data from the database for the VBA
    Dim db As DAO.Database
    Dim rst As DAO.Recordset
    Dim strSQL As String

    'Open connection to current Access database
    Set db = CurrentDb()

    'Declarations for variables to deal with dates
    Dim CurrentDate As Date
    Dim NextDateOut As Date
    Dim NextDateIn As Date
    Dim LastDateOut As Date
    Dim LastDateIn As Date

    'Setting a consistant value, technically not a constant value since there's no "const"
    CurrentDate = Date

    'Will take this out eventually
    MsgBox (CurrentDate)

    strSQL = "SELECT Next Date Out FROM Tapes Where Next Date Out = CurrentDate"
    Set rst = db.OpenRecordset(strSQL, dbOpenDynaset)
    With rst
    If .RecorCount > 0 Then
        .MoveFirst
        .Edit
        !Next Date Out = (CurrentDate+20)
      .Update
    End If
    End With
End Sub

先谢谢!!!我正在取得进展,但在途中撞墙。再次感谢!!!

1 个答案:

答案 0 :(得分:0)

我认为你可以直接用查询来解决这个问题。

让我们将这个问题分成几个步骤:

如果NextDateOut(表格中的字段)等于currentDate(代码中的变量),则:

  1. 您需要将条件为真的所有记录移动到新表
  2. 对于保留在表格中的记录,您需要将LastDateOut更新为currentDate,将nextDateIn更新为currentDate + 10,将nextDateOut更新为currentDate + 20 }
  3. 如果这是正确的,你可以试试这个:

    dim strSQL as String
    dim currentDate as Date
    ...
    ' Step 1: Copy the records to a new table '
    strSQL = "insert into otherTable " & _
             "select * from tapes " & _
             "where [nextDateOut]=" & CDbl(currentDate)
    doCmd.runSQL strSQL
    
    ' Step 2: Delete the records just copied '
    strSQL = "delete from tapes where [nextDateOut]=" & CDbl(currentDate)
    doCmd.runSQL strSQL
    
    ' Step 3: Update the dates in ALL the records remaining the "tapes" table '
    strSQL = "update tapes " & _
             "set [lastDateOut]=" & CDbl(currentDate) & ", " & _
             "set [nextDateIn]=" & CDbl(currentDate + 10) & ", " & _
             "set [nextDateOut]=" & CDbl(currentDate + 20)
    doCmd.runSQL strSQL
    ...
    

    注意:我使用CDbl(currentDate)来避免日期格式出现问题(MS Access将日期存储为双精度值,整数部分代表天数,小数部分代表天数分数)< / p>

    希望这有助于你