2013-07-29 83 views
1

我可以在日期之间进行搜索,但是如果我只想从开始日期和之后搜索。如何搜索从开始日期到结束日期?

过去几个星期,我一直在尝试自学VBA和SQL ...这是一个工作进度。

If Me.tb_dateRange1 <> "" And Me.tb_dateRange2 <> "" Then 

    Dim LYear As Integer 
    Dim thisDate As Date 

    startDate = Me.tb_dateRange1 
    endDate = Me.tb_dateRange2 
    LYear = Year(endDate) 

    If variationNumber = 0 Then 
     sqlDateRange = " WHERE " & sqlDateRange 
    Else 
     sqlDateRange = " AND " & sqlDateRange 
    End If 

    'No end date conditions 
    If endDate <> "" Then 
     sqlDateRange = sqlDateRange & " Between #" & startDate & "# And #" & endDate & "#" 
    Else 
     'thisDate = #12/12/2223# 
     sqlDateRange = sqlDateRange & " >= #" & startDate & "#" 
    End If 

    sqlMiddle = sqlMiddle & sqlDateRange 
    variationNumber = variationNumber + 1 
End If 
+0

我编辑了代码,它不会再引发错误。现在没有反应。 – trama

回答

0

看来你的目标是建立一个基于两个文本框一个WHERE条款,但只有那些包含的值。

我不理解你的代码,所以会为您提供这个的做法,用样表在Access 2007

Const cstrFormat As String = "\#yyyy-mm-dd\#" 
Dim strWhere As String 

strWhere = vbNullString ' make it explicit 
If IsDate(Me.tb_dateRange1) = True Then 
    strWhere = "field_name >= " & Format(Me.tb_dateRange1, cstrFormat) 
End If 
If IsDate(Me.tb_dateRange2) = True Then 
    ' add AND if we got something from the first text box 
    If Len(strWhere) > 0 Then 
     strWhere = strWhere & " AND " 
    End If 

    strWhere = strWhere & "field_name <= " & _ 
     Format(Me.tb_dateRange2, cstrFormat) 
End If 
If Len(strWhere) > 0 Then 
    ' add WHERE 
    strWhere = "WHERE " & strWhere 
End If 

测试您的字段的名称替换FIELD_NAME。如果除了日期之外还需要评估时间,请更改格式常量。

cstrFormat As String = "\#yyyy-mm-dd hh:nn:ss\#" 

我没有你将如何使用WHERE字符串,所以我就在MsgBox显示。

If Len(strWhere) > 0 Then 
    MsgBox strWhere 
Else 
    MsgBox "no dates, so no WHERE" 
End If 
1

你要寻找的是大于或等于起始日期值:

sqlDateRange = sqlDateRange & " >= #" & startDate & "#" 

访问SQL是很讲究的日期格式,它将接受:

sqlDateRange = sqlDateRange & " >= #" & Format(startDate, "mm/dd/yyyy") & "#" 

或者,如果有必要,

sqlDateRange = sqlDateRange & " >= #" & Format(startDate, "yyyy-mm-dd") & "#" 

(ISO标准日期表示法)

+0

我编辑了你的建议,它仍然没有搜索超出开始日期。 – trama

+0

我已添加到我的答案中。 –

+1

如果你没有得到结果,也许没有合格的数据。在您的应用程序中尝试之前,直接针对数据库运行您的查询。 –

相关问题