VBA/MSACCESS/SQL query greater than or equal to - sql

When I click a button in Excel, I have the query below that retrieves data from an Access DB.
It pulls data based on a date in a particular cell. This works fine.
However, the query is not able to retrieve based on the "greater than or equal to" condition.
It only pulls dates "equal to" what's in that cell reference.
Dim N As Date
N = Sheets("sheet1").Range("h3")
rs.Open "SELECT SID, Requestor, Comments, Updated_Date, Updated_By FROM CL WHERE datevalue(Updated_Date) >= '" & N & "'", cn

datevalue(Updated_Date) returns a Date/Time value. So compare it to a Date/Time value instead of a string. Use # characters to delimit the Date/Time value.
Dim strSelect As String
strSelect = "SELECT SID, Requestor, Comments, Updated_Date, Updated_By " & _
"FROM CL WHERE datevalue(Updated_Date) >= " & Format(N, "\#yyyy-m-d\#")
rs.Open strSelect, cn

Related

How to import a microsoft access query with input parameters into excel

I have to import a microsoft access query into Excel.
The issue that I have with the import is that the Microsoft Access query requires two input parameters, i.e current month and previous month.
Based on the input, the Access query will select certain values from a table that fit the criteria and then make certain calculations only for these values.
If I use the import function in Excel I receive an error which states that two inputs were expected but not given.
Any help would be appreciated greatly.
Thank you!
MS Access sql code is similar to this:
Select
table1.value,
table2.value,
table1.value * table2.value as product,
From(
select *
(from table 1 where date = current month)
inner join
select *
(from table 2 where date = previous month))
(current and previous month are popup input variables)
The Access query object cannot have dynamic parameters. Excel will have to provide the criteria. Following is an example of Excel pulling data from Access.
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
Set cn = New ADODB.Connection
Set rs = New ADODB.Recordset
cn.Open ""Provider=Microsoft.ACE.OLEDB.12.0; Data Source='C:\Users\June\LabData.accdb'"
strStateNum = InputBox("Enter State Number", "State Number")
rs.Open "SELECT * FROM GeoDataAll WHERE StateNum='" & strStateNum & "';", cn, adOpenStatic, adLockReadOnly
Instead of InputBox, can reference cell to provide parameter.
Your query in Excel like:
rs.Open "SELECT Q1.*, field1 * field2 AS Product FROM (" & _
"(SELECT * FROM table1 WHERE [date] = " & cell for current month & ") AS T1 " & _
"INNER JOIN " & _
"(SELECT * FROM table2 WHERE [date] = " & cell for previous month & ") AS T2 " & _
"ON T1.ID=T2.ID) " & _
"AS Q1;", cn, adOpenStatic, adLockReadOnly
Then use CopyFromRecordset method to write the data to a range on worksheet.

Date Order in Cross Tab Query - use Separate Table to Sort

I have a cross tab query with 'mmm-yyyy' formatted dates for Fields in the Columns.
I have used the below Design to create the query.
Cross Tab Design View
The problem I am having is the dates are not sorting correctly from Dec-17 down to Jul-16 in descending order. This is going to be a dynamic query with months changing every month so I want to use an additional table of data to do the sorting (as opposed to entering a list of month names in the Properties window).
How would I fix my query to get it to do this please?
Thanks for your help
Unfortunately, no matter how joined tables are sorted, crosstab will sort columns by default in alphabetical order, hence Apr, Dec, ... begins the order. To change or even filter column order in crosstabs, you would specify values in PIVOT Col IN () clause of SQL statement.
Since you need a dynamic query consider creating a querydef in VBA to update the SQL behind the crosstab where you dynamically update the PIVOT Col IN () clause. Of course, pass begin and end dates as needed or by parameters:
Public Sub BuildCrossTab()
Dim db As Database
Dim qdef As QueryDef
Dim strSQL As String, dates As String
Dim i As Integer, monthsDiff As Integer
Set db = CurrentDb
' DELETE PREVIOUS SAVED QUERY
For Each qdef in db.QueryDefs
If qdef.Name = "AccuralsCrosstabQ" Then
db.Execute "DROP Table " & qdef.Name, dbFailOnError
End If
Next qdef
' LOOP THROUGH ALL MONTHS BACKWARDS
dates = "("
monthsDiff = DateDiff("m", #7/1/2016#, #12/1/2016#)
For i = monthsDiff To 0 Step -1
dates = dates & " '" & Format(DateAdd("m", i, #7/1/2016#), "mmm-yyyy") & "',"
Next i
dates = dates & ")"
dates = Replace(dates, ",)", ")")
' PREPARE SQL STRING
strSQL = "TRANSFORM SUM(a.[Amount $]) AS SumAmount" _
& " SELECT a.Company, a.[Accrual ID], SUM(a.[Amount $]) As [Total Amount $]" _
& " FROM [Accruals Raw Data] a " _
& " GROUP BY a.Company, a.[Accrual ID]" _
& " PIVOT Format(a.[Posted Date], ""mmm-yyyy"")" _
& " IN " & dates
' CREATE QUERY
Set qdef = db.CreateQueryDef("AccuralsCrosstabQ", strSQL)
Set qdef = Nothing
Set db = Nothing
End Sub

MS Access VBA, not getting results when running DoCmd to find a record

I am not a programmer by any means but I am trying to get a small data collection database going. I need to find a record based on input. Ive got two criteria that I want it to find, and if both arent found together, it is supposed to create a new record (with both fields filled out to prevent duplication of the pair). First criteria is that it needs to look for a date. I figured that one out already, here is the code.
Dim Date1 As String
Date1 = Text6.Value
DoCmd.OpenForm "Data", , , "Data![ShiftDate] = #" & Date1 & "#"
Works like a charm. Now, I tried to add the second criteria in. The second criteria pulls from a listbox, either Day or Night. Then, it is supposed to search my data fields for that same criteria in a list box on my Data! form.
Dim Date1 As String
Dim Shift1 As String
Date1 = Text6.Value
Shift1 = List12.Column(1)
MsgBox Shift1
DoCmd.OpenForm "Data", , , _
"Data![ShiftDate] = #" & Date1 & "# AND Data![Shift] ='" & Shift1 & "'"
the msgbox was just to verify that it is pulling the right words, day or night. Everything works great, but instead of pulling a record on the right date, and with the right shift, I get blank records. I tried taking out the first half of the where statement to isolate the shift part and still just cannot get it to find a record. I have no idea what I am doing wrong.
It seems that you already have a form.
I recommend you trying this:
Add a button with a click event to the form and add following code to the click event:
dim rs as dao.recordset
set rs = currentdb.openrecordset ("SELECT * FROM [yourtable] WHERE ('ShiftDate' = '" & [yourParameter] & "' AND 'Shift' = '" & [your2ndParameter] & "')")
if rs.eof then
' here NO record is found
currentdb.execute ("INSERT INTO [yourtable] ('ShiftDate', 'Shift') VALUES ('" & [yourParameter] & "', '" & [your2ndParameter] & "')")
else
' here a record is found
endif
Since your ShiftDate is a date you need to convert your date to a SQL date Format, like this:
Function SQLDatum(Datumx) As String
If IsDate(Datumx) Then
SQLDatum = Format(CDate(Datumx), "\#yyyy-mm-dd\#", vbMonday, _
vbFirstFourDays)
Else
SQLDatum = ""
End If
End Function
In your command
DoCmd.OpenForm "Data", , , "Data![ShiftDate] = #" & Date1 & "# AND ...
You open a form Data but at the same time you specify a filter by referring to the form which is being opened with Data![ShiftDate]. This is very strange, since the filter must be applied to the data source. I would simply write
DoCmd.OpenForm "Data", , , "ShiftDate= #" & Date1 & "# AND Shift= '" & Shift1 & "'"
by referring to the table columns of the data source (on the left side of =).
Note that the column Shift must be a text column. If it was some number, you would have to drop the single quotes and pass it a corresponding id.

Access Date greater than symbol is not working

we are using Macro to retrieve data from MS Access using Query. I have used greater than symbol ">" and i have also used "#" symbol to denote time. However, It is not retriving the actual result. It is taking only the current month value. But it is not considering value for the next month values.
Please help us in resolving the issue
expiry = "29/06/2016"
expiry = CDate(expiry)
sql = "select sum(quantity) from table1 where symbol = """ & symbol & """ and symbol_type=""TF"""
sql = sql & " and expiry_date > #" & expiry & "#;"
Dim rs As Recordset
Set rs = db.OpenRecordset(sql)
If Not rs.EOF Then
If Not IsNull(rs(0)) Then
pos_lookup = rs(0)
end if
' Debug.print sql
select sum(quantity) from table1 where symbol = "NET" and symbol_type="TF" and expiry_date > #29/06/2016#;
The issue was with the data type of the field. It was "Text". It works now that I changed it to "Date/Time" data type.

How to "order by" a column and "Include Column Name with query"?

I am trying to run a sql query in excel and I want to :
1. order the query result by my column "Stationname"
2. include the column names with the query
Right now it is returning all the columns without the column name, and the end users do not know what it is.
Could someone please help? I am stuck! Below is my current code:
strQuery = "select pipelineflow.lciid lciid, ldate, volume, capacity, status, " & _
"pipeline, station, stationname, drn, state, county, owneroperator, companycode, " & _
"pointcode, pointtypeind, flowdirection, pointname, facilitytype, pointlocator, " & _
"pidgridcode from pipelineflow, pipelineproperties " & _
"where pipelineflow.lciid = pipelineproperties.lciid " & _
"and pipelineflow.audit_active = 1 " & _
"and pipelineproperties.audit_active =1 " &
_
"and pipelineflow.ldate " & dtInDate & _
"and pipelineproperties.stationname = '" & Stationname & "' "
For part 1 of your question, add an ORDER BY clause to your query. In this case: order by stationname
Part 2: Not sure why column names aren't being included in your query. You can explicitly name a column using something like the following (purely an example):
select mycolumn as "MyCustomizedColumnName" from mytable
That allows you to give columns names of your choosing. Having said that, you shouldn't be required to do so for every column, so I suspect something else is going on in your case.
I should probably add that a stored procedure (rather than dynamic SQL) will yield better runtime performance.
For ordering just put
Order By stationname
at the end of the Query.
You can iterate through the column names by using:
rst(1).Name
where rst is your recordset, and the number is the index of the column.
To sort your query results , use 'ORDER BY' at the end of the query. The last lines of your query would look like this
"and pipelineproperties.stationname = '" & Stationname & "' " & _
"ORDER BY pipelineproperties.stationname"
The column heading are returned in your query data, but not automatically written to the Excel worksheet. The code snippet below shows how to loop through the recordset's column headings and write them to the active cell's row.
'rst' refers to your recordset, update the name as required.
If Not rst.EOF Then
For x = 0 To rst.Fields.Count - 1
With ActiveCell.Offset(0, lcount)
.Value = rst.Fields(x).Name
End With
Next
End If
Make sure that you offset down from the active cell when writing the query results to the worksheet, otherwise your headings will be overwritten by the data.
Activecell.Offset(1,0).CopyFromRecordset rst