我可以在IF语句中使用DoCmd方法吗?

时间:2014-01-02 19:27:31

标签: vba ms-access if-statement methods access-vba

我有一个.mdb访问文件的以下VBA代码:

If DoCmd.RunSQL "SELECT DISTINCT Max(wk_ending_dt) FROM d2s_loader_performance" < (Date()-Weekday(Date())) Then
    DoCmd.RunSQL "DELETE * FROM d2s_loader_performance_tbl WHERE wk_ending_dt = (Date()-Weekday(Date())-35)"
End If

然后突出显示以下文字:"SELECT DISTINCT Max(wk_ending_dt) FROM d2s_loader_performance"并提供错误Compile Error: Expected Then or GoTo

有什么想法吗?我在条件检查结束时有一个Then,据我所知,双引号仅用于SQL语法。我正在使用此If...Then条件仅在最大表日期小于前一周的结束日期时才允许删除记录。

2 个答案:

答案 0 :(得分:2)

你可能需要以这种方式攻击它:

Dim db as Database
Dim rec as Recordset

Set db = CurrentDB
Set rec = db.OpenRecordset ("SELECT DISTINCT Max(wk_ending_dt) FROM d2s_loader_performance")

If rec(0) < (Date()-Weekday(Date())) Then
    DoCmd.RunSQL "DELETE * FROM d2s_loader_performance_tbl WHERE wk_ending_dt = #" & (Date()-Weekday(Date())-35) & "#"
EndIf

我假设“(Date() - Weekday(Date()) - 35)”part应该是一个计算,所以你需要用&符号(&amp;)包围它,并且在Access中的日期总是如果它们是真正的日期字段,则需要在它们之前和之后有井号(#)。

答案 1 :(得分:1)

问题是您只能使用DoCmd.RunSQL执行操作查询。因此,您无法执行Select语句。有关详细信息,请参阅this

我的方法是使用这样的东西:

Sub SqlExecute()

    Dim db As DAO.Database 
    Dim rsttemp As DAO.Recordset  
    Set db = CurrentDB
    sql = "SELECT DISTINCT Max(wk_ending_dt) FROM d2s_loader_performance"
    Set rsttemp = db.OpenRecordset(sql, dbOpenSnapshot)


    If rsttemp(0)<(Date()-Weekday(Date())) Then
        DoCmd.RunSQL "DELETE * FROM d2s_loader_performance_tbl WHERE wk_ending_dt #=" & (Date()-Weekday(Date())-35) & "#"
    End If
    Set rsttemp = Nothing

End Function