测试字段是否为空ms访问

时间:2013-03-07 21:46:57

标签: vba ms-access

我试图在MS Access中创建一个SQL语句,它将在表中查找空白字段。比如说,患者的姓氏丢失了 - 这个查询应该选择这个。

我该怎么做呢?我能够确定如何为第一个记录执行此操作,但整个表格难以确定

Dim Rst As recordSet
Dim f As Field

'Current Record set
Set Rst = CurrentDb.OpenRecordset("tblWebMeetingData")

'Holds current fields data
Dim fieldData

'With Rst
    'Do Until Rst.EOF
       For Each f In Rst.Fields
            If IsNull(f.Value) Then
                MsgBox ("Field Name: " & f.Name)
            End If
       Next
    'Loop
'End With

Rst.Close

3 个答案:

答案 0 :(得分:2)

更优雅:

Dim i As String
i = "tblWebMeetingData"
Dim j As Integer
Dim rst As Recordset

' For each Field in the table
For j = 0 To CurrentDb.TableDefs(i).Fields.Count - 1
    ' Return the number of lines that are null
    Set rst = CurrentDb.OpenRecordset("SELECT count(*) FROM " & CurrentDb.TableDefs(i).Name & " WHERE " & CurrentDb.TableDefs(i).Fields(j).Name & " IS NULL")
    rst.MoveFirst
    ' Check if it's more than one
    If rst.Fields(0).Value > 0 Then
        MsgBox CurrentDb.TableDefs(i).Fields(j).Name
    End If
Next

答案 1 :(得分:2)

在我看来,如果您在MoveNext之前使用Loop,那么您的代码就可以执行您想要的操作。我在这个版本中做了一些其他的小改动。

Dim Rst As DAO.recordSet
Dim f As DAO.Field
Dim db As DAO.Database

'Current Record set
Set db = CurrentDb
Set Rst = db.OpenRecordset("tblWebMeetingData", dbOpenTable, dbOpenSnapshot)

With Rst
    Do While Not .EOF
       For Each f In .Fields
            If IsNull(f.Value) Then
                MsgBox "Field Name: " & f.Name
            End If
       Next
       .MoveNext
    Loop
End With

Rst.Close

但是,在您提出的问题中,您要“在MS Access中创建一个将在表格中查找空白字段”的SQL语句。但是,您向我们展示了检查DAO.Recordset的VBA代码,而不是查询。我不确定你真正想要的是什么。

答案 2 :(得分:1)

为什么不呢:

Public Sub CheckNull(FieldName as String)
    Dim rs as DAO.RecordSet

    Set rs = CurrentDB.OpenRecordset("SELECT IDField FROM tblMyTable WHERE " & FieldName & " Is Null")

    If rs.eof then exit sub

    Do until rs.Eof
        debug.print rs!IDField
        rs.movenext
    Loop
End Sub

这应该在代码查找 FieldName 为空的所有记录,然后将结果打印到您将FieldName作为字符串传递的即时窗口。