我想检查访问表中是否存在字段。即使该字段不存在,我也会收到“找到”消息。
Sub test()
With Acon
.Provider = "Microsoft.ACE.OLEDB.12.0"
.ConnectionString = "Data Source=" + myFileNameDir
.Properties("Jet OLEDB:Database Password") = "synpass"
.Open
End With
With rs
.CursorLocation = adUseClient
.CursorType = adOpenDynamic
.LockType = adLockOptimistic
.ActiveConnection = Acon
.Source = "Select Distinct [Term - Phases] from Sheet1"
.Open
End With
On Error Resume Next
If rs.Fields("Start_Date") Then
MsgBox "Found"
Else: MsgBox "not fund"
End If
On Error GoTo 0
rs.Close Acon.Close
End Sub
答案 0 :(得分:1)
免责声明我不习惯使用Microsoft.ACE.OLEDB中的字段,并且以下代码未经测试
代替使用:
On Error Resume Next
If rs.Fields("Start_Date") Then
MsgBox "Found"
Else: MsgBox "not fund"
End If
On Error GoTo 0
尝试将字段分配给变量,然后进行测试:
Dim testField as Variant
On Error Resume Next
Set testField = rs.Fields("Start_Date")
On Error GoTo 0
If testField is Nothing Then 'Or is Empty
MsgBox "Found"
Else: MsgBox "not fund"
End If
在On Error Resume Next
语句周围使用If
时,条件导致错误,那么代码将假定条件已满足并失败。