在vba SQL查询上运行IF,ELSE stement

时间:2017-09-25 22:52:43

标签: excel-vba if-statement access-vba vba excel

我想在使用VBA从Excel和Access之间的连接运行的SQL查询上运行下面的IF,ELSE语句。知道为什么这不起作用吗?

 Dim myValue As String
 myValue = "CS-SS-22"
 Set cn = New ADODB.Connection
 cn.Open "Provider=Microsoft.ACE.OLEDB.12.0; " & _
 "Data Source=Q:\TOC Contract Screenings\ScreeningLogDatabase.accdb"
 Set rs = New ADODB.Recordset

 If rs.Open("Select count([ChangeScreeningNumber]) From [ScreeningLogsTEST] Where [ChangeScreeningNumber] = '" & myValue & "'", ActiveConnection:=cn, CursorType:=adOpenDynamic, LockType:=adLockOptimistic) = 0 Then MsgBox "New"
 Else
 MsgBox "Already exists"

1 个答案:

答案 0 :(得分:1)

不太确定你追求的是什么,但它可能是这样的:

Set rs = New ADODB.Recordset

rs.Open "Select Count([ChangeScreeningNumber]) From [ScreeningLogsTEST] Where [ChangeScreeningNumber] = '" & myValue & "'", ActiveConnection:=cn, CursorType:=adOpenDynamic, LockType:=adLockOptimistic

If rs.RecordCount = 0 Then 
    MsgBox "New"
Else
    MsgBox "Already exists"
End If