用常数值替换 table 中多列的空值

Replacing null values for multiple columns in a table with a constant value

我正在尝试 运行 一个脚本,该脚本将 table 中的所有空值替换为 MS Access 2007 中的常量值。我完全知道这可以使用更新查询来完成.但是我需要一次单击所有列的要求。我认为 find/replace 可以做到这一点,但我仍然希望尽量减少过程中的任何手动工作。

我尝试使用此代码,但是当我尝试 运行 它时,它什么也没做。它甚至不会触发错误。

Sub replacingnulls()

Dim dbs As DAO.Database
Dim rs As DAO.Recordset
Dim fld As DAO.Field

Set dbs = CurrentDb
Set rs = dbs.OpenRecordset("testtable", dbOpenTable)

If Not (rs.EOF And rs.BOF) Then
    rs.MoveFirst
    Do Until rs.EOF = True
            rs.Edit

        For Each fld In rs.Fields

            If IsNull(fld.Value) Then
                fld.Value = 555

            End If
        Next fld
        rs.MoveNext
  Loop
Else
    MsgBox ("There are no records")
End If

rs.Close

End Sub

调用 rs.Update 以保存您在移动到下一条记录之前对当前记录所做的更改。

Next fld
rs.Update ' <-- add this
rs.MoveNext

您可以为每个字段执行一个 UPDATE,而不是遍历 table 行然后遍历每一行中的每个字段。

Const cstrTable As String = "testtable"
Dim db As DAO.Database
Dim fld As DAO.Field
Dim tdf As DAO.TableDef
Dim strUpdate As String

Set db = CurrentDb
Set tdf = db.TableDefs(cstrTable)
For Each fld In tdf.Fields
    ' Access will complain if you attempt an UPDATE on an autonumber field,
    ' so skip field with dbAutoIncrField attribute
    If Not ((fld.Attributes And dbAutoIncrField) = dbAutoIncrField) Then
        strUpdate = "UPDATE [" & cstrTable & "] SET [" & fld.Name & _
            "] = 555 WHERE [" & fld.Name & "] Is Null;"
        'Debug.Print strUpdate
        db.Execute strUpdate, dbFailOnError
    End If
Next

请注意,无论字段的数据类型如何,代码都会尝试将所有空值替换为 555。如果所有字段都是纯数字,那可能没问题。但是,带有 Null 的 Date/Time 字段将变为 Jul 8 1901 00:00:00。 OTOH,你的记录集方法会做同样的事情......所以如果在那里没问题,在这里也应该没问题。