How to retrieve data between from date to system date using excel VBA (Automation Error) - sql

I am trying to extract a data from an Excel through different Excel using ADODB.Connection but when I am trying to retrieve data between from date to system date I am getting an automation error in Excel.
I have checked various articles but I'm unable to validate those condition because I don't have SQL Server so I am directly putting into Excel coding but again same error I am getting.
Please help......
Sub get_data()
Dim strSQL As String
Dim cnn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim DBPath As String
Dim sconnect As String
DBPath = "\\abc\Quality Report.xlsx"
sconnect = "Provider=MSDASQL.1;DSN=Excel Files;DBQ=" & DBPath & ";HDR=Yes';"
cnn.Open sconnect
strSQL = "SELECT * FROM [Error_Log$] WHERE "
If cboprocess.Text <> "" Then
strSQL = strSQL & " [Process]='" & cboprocess.Text & "'"
End If
If cboaudittype.Text <> "" Then
If cboprocess.Text <> "" Then
strSQL = strSQL & " AND [Audit_Type]='" & cboaudittype.Text & "'"
Else
strSQL = strSQL & " [Audit_Type]='" & cboaudittype.Text & "'"
End If
End If
If cbouser1.Text <> "" Then
If cboprocess.Text <> "" Or cboaudittype.Text <> "" Then
strSQL = strSQL & " AND [User_Name]='" & cbouser1.Text & "'"
Else
strSQL = strSQL & " [User_Name]='" & cbouser1.Text & "'"
End If
End If
If cborptmgr.Text <> "" Then
If cboprocess.Text <> "" Or cboaudittype.Text <> "" Or cbouser1.Text <> "" Then
strSQL = strSQL & " AND [Reporting_Manager]='" & cborptmgr.Text & "'"
Else
strSQL = strSQL & " [Reporting_Manager]='" & cborptmgr.Text & "'"
End If
End If
If cbotranstyp.Text <> "" Then
If cboprocess.Text <> "" Or cboaudittype.Text <> "" Or cbouser1.Text <> "" Or cborptmgr.Text <> "" Then
strSQL = strSQL & " AND [Transaction_Type]='" & cbotranstyp.Text & "'"
Else
strSQL = strSQL & " [Transaction_Type]='" & cbotranstyp.Text & "'"
End If
End If
If cboperiod.Text <> "" Then
If cboprocess.Text <> "" Or cboaudittype.Text <> "" Or cbouser1.Text <> "" Or cborptmgr.Text <> "" _
Or cbotranstyp.Text <> "" Then
strSQL = strSQL & " AND [Period]='" & cboperiod.Text & "'"
Else
strSQL = strSQL & " [Period]='" & cboperiod.Text & "'"
End If
End If
If cbolocation.Text <> "" Then
If cboprocess.Text <> "" Or cboaudittype.Text <> "" Or cbouser1.Text <> "" Or cborptmgr.Text <> "" _
Or cbotranstyp.Text <> "" Or cboperiod.Text <> "" Then
strSQL = strSQL & " AND [Location]='" & cbolocation.Text & "'"
Else
strSQL = strSQL & " [Location]='" & cbolocation.Text & "'"
End If
End If
If cbofatnfat.Text <> "" Then
If cboprocess.Text <> "" Or cboaudittype.Text <> "" Or cbouser1.Text <> "" Or cborptmgr.Text <> "" _
Or cbotranstyp.Text <> "" Or cboperiod.Text <> "" Or cbolocation.Text <> "" Then
strSQL = strSQL & " AND [Fatal_NonFatal]='" & cbofatnfat.Text & "'"
Else
strSQL = strSQL & " [Fatal_NonFatal]='" & cbofatnfat.Text & "'"
End If
End If
If cbostatus.Text <> "" Then
If cboprocess.Text <> "" Or cboaudittype.Text <> "" Or cbouser1.Text <> "" Or cborptmgr.Text <> "" _
Or cbotranstyp.Text <> "" Or cboperiod.Text <> "" Or cbolocation.Text <> "" Or cbofatnfat.Text <> "" Then
strSQL = strSQL & " AND [Remarks]='" & cbostatus.Text & "'"
Else
strSQL = strSQL & " [Remarks]='" & cbostatus.Text & "'"
End If
End If
If txtfromauditdt.Text <> "" Then
If cboprocess.Text <> "" Or cboaudittype.Text <> "" Or cbouser1.Text <> "" Or cborptmgr.Text <> "" _
Or cbotranstyp.Text <> "" Or cboperiod.Text <> "" Or cbolocation.Text <> "" Or cbofatnfat.Text <> "" _
Or cbostatus.Text <> "" Then
strSQL = strSQL & " AND [Audit_Date] BETWEEN '" & txtfromauditdt.Text & "' AND GETDATE()"
Else
strSQL = strSQL & " [Audit_Date] BETWEEN '" & txtfromauditdt.Text & "' AND GETDATE()"
End If
End If
Debug.Print strSQL
Set rs.ActiveConnection = cnn
rs.Open strSQL, cnn
Sheet1.Range("A42").CopyFromRecordset rs
rs.Close
cnn.Close
End Sub
Below is debug print from strsql
SELECT *
FROM [Error_Log$]
WHERE [Audit_Date] BETWEEN '16-Nov-2015' AND getdate()
Error screenshot

I think your problem is GetDate()
Your approach to building the WHERE clause can also be much simpler:
Sub get_data()
Dim strSQL As String, strWhere As String
Dim cnn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim DBPath As String
Dim sconnect As String
DBPath = "\\abc\Quality Report.xlsx"
sconnect = "Provider=MSDASQL.1;DSN=Excel Files;DBQ=" & DBPath & ";HDR=Yes';"
cnn.Open sconnect
strSQL = "SELECT * FROM [Error_Log$] WHERE "
strWhere = ""
BuildWhere strWhere, cboprocess.Text, "Process"
BuildWhere strWhere, cboaudittype.Text, "Audit_Type"
BuildWhere strWhere, cbouser1.Text, "User_Name"
BuildWhere strWhere, cborptmgr.Text, "Reporting_Manager"
BuildWhere strWhere, cbotranstyp.Text, "Transaction_Type"
BuildWhere strWhere, cboperiod.Text, "Period"
BuildWhere strWhere, cbolocation.Text, "Location"
BuildWhere strWhere, cbofatnfat.Text, "Fatal_NonFatal"
BuildWhere strWhere, cbostatus.Text, "Remarks"
If txtfromauditdt.Text <> "" Then
strWhere = strWhere & IIf(strWhere <> "", " AND ", "") & "[Audit_Date] BETWEEN '" & _
txtfromauditdt.Text & "' AND #" & Format(Date, "mm/dd/yyyy") & "# "
End If
strSQL = strSQL & strWhere
Debug.Print strSQL
Set rs.ActiveConnection = cnn
rs.Open strSQL, cnn
Sheet1.Range("A42").CopyFromRecordset rs
rs.Close
cnn.Close
End Sub
Sub BuildWhere(ByRef strWhere As String, v As String, fld As String)
If v <> "" Then
strWhere = strWhere & IIf(strWhere <> "", " AND ", "") & _
"[" & fld & "] = '" & v & "'"
End If
End Sub

Finally found out the error cause...
Actually the error was because of the quotes '13-nov-15' which I was using in coding but the same was replacing after with #13-nov-15#. It worked.
As per the #Williams answer's there was a only one correction made for another date but for parameter date the quotes was coming but now its working cool. Thanks to Tim Williams..helps a lot....

You surrounded the first text date with single quotes ', this will make it a string. You need to use the number sign # instead, like this:
Or cbostatus.Text <> "" Then
strSQL = strSQL & " AND [Audit_Date] BETWEEN #" & txtfromauditdt.Text & "# AND GETDATE()"
Else
strSQL = strSQL & " [Audit_Date] BETWEEN #" & txtfromauditdt.Text & "# AND GETDATE()"
End If

Related

VBA Runtime error While str sql grouping a value

I am writing below code but showing error can anyone help me
Private Sub cmdShowData_Click()
'populate Data
strSQL = "SELECT [OverseasAgent],SUM([Weight]) As [Total] FROM [data$] WHERE "
If cmbNetwork.Text <> "" Then
strSQL = strSQL & " Format([JobDate], 'MMM/YYYY')='" & cmbNetwork.Text & "'"
End If
If cmbOrigin.Text <> "" Then
If cmbNetwork.Text <> "" Then
strSQL = strSQL & " AND [Branch]='" & cmbOrigin.Text & "'"
Else
strSQL = strSQL & " [Branch]='" & cmbOrigin.Text & "'"
End If
End If
If cmbDestination.Text <> "" Then
If cmbNetwork.Text <> "" Or cmbOrigin.Text <> "" Then
strSQL = strSQL & " AND [Destn]='" & cmbDestination.Text & "'"
Else
strSQL = strSQL & " [Destn]='" & cmbDestination.Text & "'"
End If
End If
If cmdCountry.Text <> "" Then
If cmbNetwork.Text <> "" Or cmbOrigin.Text <> "" Or cmbDestination.Text <> "" Then
strSQL = strSQL & " AND [Country]='" & cmdCountry.Text & "'"
Else
strSQL = strSQL & " [Country]='" & cmdCountry.Text & "'"
End If
End If
If cmbNetwork.Text <> "" Or cmbOrigin.Text <> "" Or cmbDestination.Text <> "" Or cmdCountry.Text <> "" Then
'now extract data
closeRS
OpenDB
rs.Open strSQL, cnn, adOpenKeyset, adLockOptimistic
If rs.RecordCount > 0 Then
Sheets("View").Visible = True
Sheets("View").Select
Range("dataSet").Select
Range(Selection, Selection.End(xlDown)).ClearContents
'Now putting the data on the sheet
ActiveCell.CopyFromRecordset rs
Else
MsgBox "I was not able to find any matching records.", vbExclamation + vbOKOnly
Exit Sub
End If
End If
End Sub
It seems that "OverseasAgent" is in the SELECT as the query starts with "SELECT [OverseasAgent],SUM([Weight]) As [Total] FROM [data$] WHERE", but it is not part of the aggregate function SUM().
Try changing the query without the SUM() initially to see what yu are getting. Then add it back and add the Group By OversearsAgent part. And in general, try running the query hard-coded initially, without all the conditions, coming from a form.
In order to understand exactly what is wrong with the query, write MsgBox strSQL before the rs.Open strSQL and see how the query looks like. Then examine further.

Unable to Filter

I am trying to write an SQL code in my MS Access database whereby the filter on Entity_name is not working properly
Function FilterResults()
Dim strCriteria As String
strCriteria = ""
If Nz(Me.cboEntitynameFilter) <> "" Then
strEntityNameFilter = "Entity_Name = '" & Me.cboEntitynameFilter & "'"
Else
strEntityNameFilter = "Entity_Name = '*'"
End If
If Nz(Me.cboAssignmentFilter) <> "" Then
strAssignmentFilter = " AND " & "Assignment = '" & Me.cboAssignmentFilter & "'" '& " AND "
End If
If Nz(Me.cboFYFilter) <> "" Then
strFYFilter = " AND " & "Financial_Year = '" & Me.cboFYFilter & "'"
End If
strCriteria = Nz(strEntityNameFilter, "*") & Nz(strAssignmentFilter, "*") & Nz(strFYFilter, "*")
' End If
If strCriteria = ("Entity_Name = '*'") Then
Me.Filter = ""
Me.FilterOn = False
Else
If strCriteria <> "" Then
Me.Filter = strCriteria
Me.FilterOn = True
End If
End If
End Function
The strCriteria returned is
Entity_Name = '*' AND Assignment = 'MFI'
The filter doesn't work and the Entity_Name is all blank. What am I doing wrong.
I am using this in MS-Access and building query in VBA
I would do like this
Dim strCriteria AS string
strCriteria = "1 = 1"
If Len(Nz(Me.cboEntitynameFilter, "")) > 0 Then
strCriteria = strCriteria & " and [Entity_Name] = """ & Me.cboEntitynameFilter & """"
End If
If Len(Nz(Me.cboAssignmentFilter, "")) > 0 Then
strCriteria = strCriteria & " and [Assignment] = """ & Me.cboAssignmentFilter & """"
End If
If Len(Nz(Me.cboFYFilter, "")) > 0 Then
strCriteria = strCriteria & " and [Financial_Year] = """ & Me.cboFYFilter & """"
End If
Me.Filter = strCriteria
Me.FilterOn = True
if any of the combobox or textbox didn't select than it will igonre those field.

ODBC driver does not support the requested properties in EXCEL VBA

Im having a problem with this driver issues or something, here is my code, in my previous worksheet its working fine but when i copied the code and transferred it here the error pops out " Run Time Error ODBC driver does not support the requested properties" what seems to be the problem?
Dim strSQL As String
Dim cnn As ADODB.Connection
Dim rs As ADODB.Recordset
Set rs = New ADODB.Recordset
strSQL = "SELECT * FROM [Data$] WHERE "
If cmbGroup.Text <> "" Then
strSQL = strSQL & " [Group Name]='" & cmbGroup.Text & "'"
End If
If cmbPolicy.Text <> "" Then
If cmbGroup.Text <> "" Then
strSQL = strSQL & " AND [Policy Status]='" & cmbPolicy.Text & "'"
Else
strSQL = strSQL & " [Policy Status]='" & cmbPolicy.Text & "'"
End If
End If
If cmbOfficer.Text <> "" Then
If cmbGroup.Text <> "" Or cmbPolicy.Text <> "" Then
strSQL = strSQL & " AND [Case Officer]='" & cmbOfficer.Text & "'"
Else
strSQL = strSQL & " [Case Officer]='" & cmbOfficer.Text & "'"
End If
End If
If cmbGroup.Text <> "" Or cmbPolicy.Text <> "" Or cmbOfficer.Text <> "" Then
Set cnn = New ADODB.Connection
OpenDB cnn
rs.Open strSQL, cnn, adOpenKeyset, adLockOptimistic 'this code gets the error
Set cnn = Nothing
If rs.RecordCount > 0 Then
Sheets("Company View").Visible = True
Sheets("Company View").Select
Range("dataSet").Select
Range(Selection, Selection.End(xlDown)).ClearContents
ActiveCell.CopyFromRecordset rs
With Range("dataSet")
.Select
.Copy
End With
Range(Selection, Selection.End(xlDown)).PasteSpecial (xlPasteFormats)
Application.CutCopyMode = False
Else
MsgBox "I was not able to find any matching records.", vbExclamation +
vbOKOnly
Set rs = Nothing
End If
Exit Sub
End If
this one is my ADODB Connection
Private Sub OpenDB(ByRef cnn As ADODB.Connection)
cnn.ConnectionString = "Driver={Microsoft Excel Driver (*.xls, *.xlsx,
*.xlsm, *.xlsb)};DBQ=" & _
ActiveWorkbook.Path & Application.PathSeparator & ActiveWorkbook.Name
cnn.Open
End Sub
thanks!

MS Access vba export form results to excel with where condition

I have a table that has a lot of fields and then a form that takes only a few of those fields. I have a search button on the form where you can select certain records. Is there a way in VBA to export the results from the form but include all the fields from the table.
Here is my attempt from some code that I found:
Private Sub Command49_Click()
Dim strWhere As String
Dim strFile As String
Const strcStub = "SELECT * FROM tblMaster " & vbCrLf
Const strcTail = "ORDER BY ID;"
Const strcExportQuery = "Query1" 'Name of the query for exports.
'Keyword
If Nz(Me.tKW, "") <> "" Then
strWhere = strWhere & "[iavmtitle] Like '*" & Replace(Me.tKW, " '", "''") & "*' AND "
End If
'Release Date From
If Nz(Me.tRF, "") <> "" Then
strWhere = strWhere & "[releaseDate] between " & "#" & Me.tRF & "# AND #" & Me.tRT & "#" & " AND "
End If
'Expliots
If Nz(Me.cmbExploits, "") <> "" Then
strWhere = strWhere & "[knownExploits] = '" & Me.cmbExploits & "' AND "
End If
'Incidents
If Nz(Me.cmdIncidents, "") <> "" Then
strWhere = strWhere & "[knownDodIncidents] = '" & Me.cmdIncidents & "' AND "
End If
'Release Date From
If Nz(Me.txtSaveSend, "") <> "" Then
strWhere = strWhere & "[lastSaved] > " & "#" & Me.txtSaveSend & "#" & " AND "
End If
If strWhere <> "" Then
strWhere = Left(strWhere, Len(strWhere) - 5) 'Remove the extra AND
Me.Filter = strWhere
Me.FilterOn = True
Else
Me.Filter = ""
Me.FilterOn = False
End If
If Me.FilterOn Then
strWhere = "WHERE " & Me.Filter & vbCrLf
End If
CurrentDb.QueryDefs(strcExportQuery).SQL = strcStub & strWhere & strcTail
strFile = "C:\Data\MyExport.xls"
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, _
strcExportQuery, strFile
End Sub

VBA SQL query result error

There's no result or blank excel sheet in result of following SQL query. It works fine if I remove where condition but Its required. So kindly help me to correct my code with where condition. Code is follow-
Private Sub cmdOpenQuery_Click()
Dim strTableName As String
Dim strFieldName As String
Dim strFieldValue As String
Dim strFV As String
Dim strFieldType As String
Dim strBaseSQL As String
Dim strCriteria As String
Dim varItem As Variant
Dim strSQL As String
Dim qdf As DAO.QueryDef
Dim OutPut As String
Dim intCounter As Integer
Dim xlApp As Object
For Each qdf In CurrentDb.QueryDefs
If qdf.Name = "MyQry" Then
DoCmd.DeleteObject acQuery, "MyQry"
Exit For
End If
Next
strTableName = Me.[cboSelectTblQry]
strFieldName = Me.[cboWhere]
strFV = Me.[cboEqualto]
strFieldType = CurrentDb.TableDefs(Me.cboSelectTblQry).Fields(Me.cboWhere).Type
If strFieldType = 4 Then
strFieldValue = "[" & strFV & "]"
ElseIf strFieldType = 10 Then
strFieldValue = "['" & strFV & "']"
ElseIf strFieldType = 8 Then
strFieldValue = "[#" & strFV & "#]"
End If
strBaseSQL = "SELECT "
For intCounter = 0 To lstSelectTo.ListCount
lstSelectTo.Selected(intCounter) = True
Next intCounter
For Each varItem In Me![lstSelectTo].ItemsSelected
strCriteria = strCriteria & "[" & Me![lstSelectTo].ItemData(varItem) & "],"
Next
strSQL = strBaseSQL & Left$(strCriteria, Len(strCriteria) - 1) & " FROM [" & strTableName & "]" & " Where [" & strFieldName & "] = strFieldValue "
Set qdf = CurrentDb.CreateQueryDef("MyQry", strSQL)
If cboFormat = "Excel" Then
OutPut = "D:/Export_" & strTableName & "_" & Date & ".xlsx"
DoCmd.TransferSpreadsheet acExport, , "MyQry", OutPut
MsgBox " File has been exported to " & OutPut
DoCmd.Close
DoCmd.OpenForm "frmCreateQry"
Set xlApp = CreateObject("Excel.Application")
xlApp.Workbooks.Open (OutPut)
xlApp.Visible = True
ElseIf cboFormat = "PDF" Then
OutPut = "D:/Export_" & strTableName & "_" & Date & ".pdf"
DoCmd.OutputTo acOutputQuery, "MyQry", acFormatPDF, OutPut, True
MsgBox " File has been exported to " & OutPut
ElseIf cboFormat = "Word" Then
End If
ExitSub:
Exit Sub
ErrorHandler:
Resume ExitSub
End Sub
Your where condition is using strFieldValue as the value to look for. You should instead use the use held by strFieldValue for comparison. You're doing that properly with strTableName already. It is the same idea here. You'd need to enclose the value of strFieldValue in quotes when you add it.
strSQL = strBaseSQL & Left$(strCriteria, Len(strCriteria) - 1) & " FROM [" & strTableName & "]" & " Where [" & strFieldName & "] = '" & strFieldValue & "'"
I made some corrections and it's working now fine for all format like numeric, text and date type.
Following corrections made in Type condition :-
If strFieldType = 4 Then
strFieldValue = Me.cboEqualto
ElseIf strFieldType = 10 Then
strFieldValue = "'" & strFV & "'"
ElseIf strFieldType = 8 Then
strFieldValue = "#" & strFV & "#"
End If
and following correction in strSQL:-
strSQL = strBaseSQL & Left$(strCriteria, Len(strCriteria) - 1) & " FROM [" & strTableName & "]" & " Where [" & strFieldName & "] = " & strFieldValue & ""