0

好的,所以我正在尝试编写 VBA 代码以尽可能地自动化。我需要它做的是从表中的字段中读取,如果它满足条件,则将其复制到新表中。这是为了旋转的目的。如果CurrentDate等于NextDateOut该项目的任何值,我想转到某个表,但也想更新当前表中的值。 NextDateOut将是LastDateOut表中的新值,NextDateIn距 NextDateIn 10 天,从那时起NextDateOut10 天。我可以编写此数学逻辑,它只是将我的表中的值与我现在的常量进行比较,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

提前致谢!!!我正在取得进展,但在路上碰壁了。再次感谢!!!

4

1 回答 1

0

我认为您可以通过查询直接解决此问题。

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

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

  1. 您需要将条件为真的所有记录移动到新表中
  2. 对于保留在表中的记录,您需要更新LastDateOutto currentDatenextDateIntocurrentDate + 10nextDateOuttocurrentDate + 20

如果这是正确的,你可以试试这个:

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 将日期存储为双精度值,整数部分表示天数,小数部分表示天数的小数部分)

希望这可以帮助你

于 2013-01-11T21:40:39.270 回答