The SQL select statement that I created in Excel VBA is not working properly with dates. I have tried putting the date as a variable and just entering not as a variable, also with # signs and not. The statement works in that it provides results, but the dates from the [Orientation Date] column are not filtered how I want. For instance, I set strCurrentDate365 to equal to 23 Oct 2023. Then in the SQL statement I want it to return records where the [Orientation Date] is greater than strCurrentDate365, but the results includes records with all dates, lesser and greater.
Sub employeeInquiry()
Dim strCurrentDate365 As Date
strCurrentDate365 = "23 Oct 2023"
strCurrentDate365 = Format(strCurrentDate365, "mm/dd/yyyy")
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
strFile = ThisWorkbook.FullName
strCon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & strFile _
& ";Extended Properties=""Excel 12.0;HDR=Yes;IMEX=1"";"
'********************* Annual Expirations *******************
Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
cn.Open strCon
strSQL = "SELECT [Employee ID#], [Employee Name], [Company], cdate([Orientation Date]) " & _
"FROM [Training_Database$] " & _
"WHERE [Employee Name] IS NOT NULL " & _
"AND [Employee Name] <> 'blank space' " & _
"AND [Employee Name] <> 'Employee Name' " & _
"AND [Orientation Date] > #" & strCurrentDate365 & "# "
rs.Open strSQL, cn
'select and clear results sheet
Sheets("Inquiry_Results").Select
Cells.ClearContents
'row and column to insert
Dim r As Integer
r = 2
Dim c As Integer
c = 1
'insert result
Cells(r, c).CopyFromRecordset rs
rs.Close
cn.Close
End Sub
Test Table:
| Employee ID# | Employee Name | Company | Orientation Date |
|---|---|---|---|
| blank space | blank space | blank space | Lifetime |
| blank space | blank space | blank space | WFD |
| blank space | blank space | blank space | 5 hours |
| Employee ID# | Employee Name | Company | Orientation Date |
| 752856 | Smith, John | Waste LLC | 12/28/2023 |
| 685273 | Jones, Tracy | Paint & Co | 11/7/2023 |
| 385418 | Ramirez, Jen | Waste LLC | 12/23/2023 |
| 787233 | Johnson, Ted | Paint & Co | 10/7/2023 |
| 988534 | Smith, Jane | Waste LLC | 10/22/2023 |
| 438541 | Williams, Ken | PipeFab LLC | 11/18/2023 |
