2013-03-07 35 views
3

我试图在MS Access中创建一个SQL语句,它将查找表中的空白字段。例如,说一个病人的姓氏缺失 - 这个查询应该选择这个。测试字段为空ms访问

我该怎么做呢?我能确定如何做到这一点的第一条记录但对整个表被证明是难以

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 

回答

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

这工作很好,但我不得不添加[],因为一些字段名称有空格 - 荣誉! – Katana24 2013-03-07 22:16:45

+0

类型的后续行动,但我将如何去寻找这发生在确切的行? – Katana24 2013-03-07 22:28:17

+0

而不是'count(*)',您可以使用该键。它将为每个为空的字段返回密钥。然后,你必须添加一个'Do直到rst.EOF'来遍历所有的结果。 – user2088176 2013-03-08 14:21:31

2

我看来像你的代码会做你想要什么如果您在Loop之前使用MoveNext。我在这个版本中做了一些其他的小改动。

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代码。我不确定你真正想要什么。

+0

对不起糟糕的措辞 - 我的意思是关于查询的SQL代码 – Katana24 2013-03-07 22:22:25

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 

这应该在代码中查找所有记录,其中字段名为空,然后打印结果到您传递字段名作为一个字符串即时窗口。