Using a boolean function after where (SQL)? - sql

I'm trying to use a function that results a boolean after in a where in a SQL statement.
What the function does is that it verifies if the selected date is within two const dates and results a boolean. I'm having problem with the SQL syntax
Sqlstring = "Select count() from [Orders].[Date]" & _
where " & Function([Orders].[Date]) = True & ""
I'm not sure if the sql statement is correct.
Edit here's the code:
public StartDate as String
public EndDate As string
Private Function GetOrdersNumbers() As Integer
Dim rsData As ADODB.RecordSet
Dim szConnect As String
Dim szSQL As String
Dim DataSource As String
DataSource = "C:\Users\user\Desktop\db.mdb"
szConnect = "Provider=Microsoft.Jet.OLEBD.4.0;" & _
"Data Source=" & DataSource & ";" & _
"user ID=admin;password=;"
szSQL = "SELECT COUNT(*) FROM [Et_Journal Livraison Fournisseur] WHERE [Et_Journal Livraison Fournisseur].[Date] BETWEEN [#StartDate] And [#EndDate] "
Set rsData = New ADODB.RecordSet
rsData.Open szSQL, szConnect, adOpenForwardOnly, adLockReadOnly, adCmdText
If Not rsData.EOF Then
Range("A01").CopyFromRecordset RecordSet
GetOrdersNumbers = CInt(Range("A01").Value)
End If
End Function

You did not provide information about database engine... Nevertheless
I'd suggest to use query like this:
SELECT COUNT(*)
FROM Orders
WHERE [Date] BETWEEN [#date1] AND [#date2]
where
#date1 and #date1 is a parameter
There's no reason to use function.
[EDIT]
Thank you for clarification. Have a look at below code:
Option Explicit
Sub Test()
Dim d1 As Date
Dim d2 As Date
d2 = DateSerial(2015, 1, 6)
d1 = DateAdd("MM", -3, d2)
MsgBox GetOrdersNumbers(d1, d2)
End Sub
Function GetOrdersNumbers(ByVal StartDate As Date, ByVal EndDate As Date) As Long
Dim oConn As ADODB.Connection, oRst As ADODB.Recordset
Dim sConnString As String, sQry As String
Dim retVal As Long
sConnString = "Provider=Microsoft.Jet.OLEBD.4.0;" & _
"Data Source=C:\Users\user\Desktop\db.mdb;" & _
"user ID=admin;password=;"
Set oConn = New ADODB.Connection
With oConn
.ConnectionString = sConnString
.Open
End With
sQry = "SELECT [Date] As MyDate" & vbCr & _
"FROM [Et_Journal Livraison Fournisseur]" & vbCr & _
"WHERE [Et_Journal Livraison Fournisseur].[Date] BETWEEN #" & StartDate & "# And #" & EndDate & "#"
Set rsData = New ADODB.Recordset
oRst.Open szSQL, oConn, adOpenStatic, adLockReadOnly
retVal = oRst.RecordCount
End If
Exit_GetOrdersNumbers:
On Error Resume Next
oRst.Close
Set oRst = Nothing
oConn.Close
Set oConn = Nothing
GetOrdersNumbers = retVal
Exit Function
Err_GetOrdersNumbers:
MsgBox Err.Description, vbExclamation, Err.Number
Resume Exit_GetOrdersNumbers
End Function

Related

VBA & SQL how to select specific values based on range in excel?

I am newbie in connection of vba (excel) and oracle database. I have tried to look for some information but I could not find anything that would work for me.
I want to write a query that will return me only rows in which there is a specific values.
My query looks like this:
SQLStr = SQLStr = "SELECT NGKHFHCD, NGKHFNAM, NGKHGNKA, NGKHSZIC, NGKHMTRC, NGKHSNZC, NGKHGCHC, NGKHKKKS, NGKHKTKS FROM NGKH order by NGKHFHCD"
But I want to have something that will be like this SQLStr = "SELECT NGKHFHCD, NGKHFNAM, NGKHGNKA, NGKHSZIC, NGKHMTRC, NGKHSNZC, NGKHGCHC, NGKHKKKS, NGKHKTKS FROM NGKH WHERE NGKHFHCD = SHeet1(A2:A)"
I just don't want to pull out whole table from oracle, because it will take a lots of time so I thought that maybe I can return only specific rows from that table.
Also if there is no searched value in the table I would like to mark it in someway.
Is there anyway to solve it?
my code:
Sub OracleLocalConnect()
Dim RecordSet As New ADODB.RecordSet
Dim con As New ADODB.Connection
Dim ExcelRange As Range
Dim SQLStr As String
Dim ws As Worksheet
con.ConnectionString = "Provider=OraOLEDB.Oracle.1;User ID=***;Password=****;Data Source=*****;"
con.Open
Set RecordSet = CreateObject("ADODB.Recordset")
SQLStr = "SELECT GNKHFHCD, GNKHFNAM, GNKHGNKA, GNKHSZIC, GNKHMTRC, GNKHSNZC, GNKHGCHC, GNKHKKKS, GNKHKTKS FROM GNKH ORDER BY GNKHFHCD"
RecordSet.Open SQLStr, con, adOpenStatic, adLockReadOnly
Set ws = ActiveWorkbook.Sheets("Prices")
Set ExcelRange = ws.Range("A2")
ExcelRange.CopyFromRecordset RecordSet
RecordSet.Close
con.Close
Exit Sub
Exit Sub
End Sub
Untested but this would be close:
Sub OracleLocalConnect()
Dim RecordSet As New ADODB.RecordSet
Dim con As New ADODB.Connection
Dim ExcelRange As Range
Dim SQLStr As String
Dim ws As Worksheet
con.ConnectionString = "Provider=OraOLEDB.Oracle.1;User ID=***;Password=****;Data Source=*****;"
con.Open
Set RecordSet = CreateObject("ADODB.Recordset")
SQLStr = " SELECT GNKHFHCD, GNKHFNAM, GNKHGNKA, GNKHSZIC, GNKHMTRC, " & _
" GNKHSNZC, GNKHGCHC, GNKHKKKS, GNKHKTKS FROM GNKH " & _
" where " & InClause(Sheet1.Range("A2:A1000"), "GNKHFHCD", True) & _
" ORDER BY GNKHFHCD "
RecordSet.Open SQLStr, con, adOpenStatic, adLockReadOnly
Set ws = ActiveWorkbook.Sheets("Prices")
Set ExcelRange = ws.Range("A2")
ExcelRange.CopyFromRecordset RecordSet
RecordSet.Close
con.Close
End Sub
'Create an in clause for an Oracle query
Function InClause(rng As Range, colName As String, Optional quoted As Boolean = False)
'https://stackoverflow.com/questions/400255/how-to-put-more-than-1000-values-into-an-oracle-in-clause
Dim s As String, c As Range, qt As String, sep As String
qt = IIf(quoted, "'", "")
sep = ""
s = "(999, " & colName & ") in ("
For Each c In rng.Cells
If Len(c.Value) > 0 Then
s = s & sep & vbLf & "(999," & qt & c.Value & qt & ")"
sep = "," 'add comma after first pass
End If
Next c
InClause = s & ")"
End Function

SubCount Divided By Total Count

The table is named [Sheet1$]
We are working with the first column, [F1], which is populated with random numbers ranging in value from 1-20. The entire column, all 1,048,576 rows, are filled.
I want to find the percentage of rows with a value of 19
I can make separate subqueries and divide:
"Select Count([F1]) From [Sheet1$] Where [F1]=19;"
divided by
"Select Count([F1]) from [Sheet1$]
But I want to fit both queries into a single query.
EDIT:
It looks like the OLEDB precludes the use of CASE WHEN statements, but we can use IIF() statemnts
https://stackoverflow.com/a/1742005/9721351
Option Explicit
Private Declare PtrSafe Function timeGetTime Lib "winmm.dll" () As Long
Sub main()
Dim started As Long
Dim ended As Long
Dim cn As ADODB.Connection
Dim abcCount As Long
Dim pbcCount As Long
Dim strFile As String
Dim filePath As String
Dim inputDirectoryToScanForFile As String
started = timeGetTime
filePath = "Z:\Test\Test1.xlsx"
Set cn = New ADODB.Connection
cn.Open _
"Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source='" & filePath & "';" & _
"Extended Properties=""Excel 12.0 Macro;HDR=No;IMEX=1;"";"
Debug.Print findCount(cn)
cn.Close
Set cn = Nothing
ended = timeGetTime
Debug.Print "Sum found in " & (ended - started) / 1000 & " seconds"
End Sub
Function findCount(ByRef cn As ADODB.Connection) As Long
On Error GoTo CleanFail:
Dim strSql As String
Dim rs As ADODB.Recordset
Set rs = New ADODB.Recordset
strSql = "Select Count([F1]) from [Sheet1$] where [F1]=19;"
rs.Open strSql, cn
findCount = rs.GetString
rs.Close
Set rs = Nothing
Exit Function
CleanFail:
Debug.Print "nothing in file"
End Function
SELECT SUM(IIF([F1] = 19, 1 ,0)) *100.0 / SUM(IIF([F1] <> Null,1,0)) from [Sheet1$]

Export from Excel to AccessDB, error Arguments are of the wrong type, are out of acceptable range, or are in conflict with one another

I try to export some data from excel to my access database, but on line 15 rs.open I get the error Arguments are of the wrong type, are out of acceptable range, or are in conflict with one another. I can't seem to figure out what is going wrong here. Any help would be appreciated, thanks!
Public Sub updateAntibiotics(abName As String, Optional startDate As Date, Optional stopDate As Date)
Dim cn As Object, rs As Object
Dim currPath As String, DbPath As String
Dim sProduct As String, sVariety As String, cPrice As Variant
Dim patientID As Integer
' connect to the Access database
currPath = Application.ActiveWorkbook.Path
DbPath = Left$(currPath, InStrRev(currPath, "\")) & "IZ Damiaan.accdb"
Set cn = CreateObject("ADODB.Connection")
cn.Open "Provider=Microsoft.Ace.OLEDB.12.0;Data Source='" & DbPath & "';"
' open a recordset
Set rs = CreateObject("ADODB.Recordset")
rs.Open "Antibiotics", cn, adOpenKeyset, adLockOptimistic, adCmdTable
patientID = Val(Sheets("PatientData").Range("A2"))
rs.Filter = "fkPatientID='" & patientID & "' AND Antibiotic='" & abName & "' AND stopDate IS NULL"
If rs.EOF Then
Debug.Print "No existing record - adding new..."
rs.Filter = ""
rs.AddNew
rs("fkPatientID").Value = patientID
rs("Antibiotic").Value = abName
Else
Debug.Print "Existing record found..."
End If
If Not IsNull(startDate) Then rs("startDate").Value = startDate
If Not IsNull(stopDate) Then rs("stopDate").Value = stopDate
rs.Update
Debug.Print "...record update complete."
rs.Close
Set rs = Nothing
cn.Close
Set cn = Nothing
End Sub

Select SQL Statement in Excel VBA

Sub LogCheck()
Dim cn As Object
Dim rs As Object
Dim StrSql As String
Dim strConnection As String
Dim AppPath As String
Set cn = CreateObject("ADODB.Connection")
AppPath = Application.ActiveWorkbook.Path
strConnection = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=C:\ceo.accdb;"
cn.Open strConnection
S_ID = Sheets("My").Range("A1").Value
StrSql = "SELECT * FROM EDO Where ID = ' " & S_ID & " '"
rs.Open StrSql, cn
If rs = Null Then
MsgBox "Record Not found"
Else
MsgBox "Record Found"
End If
End Sub
I am unable to run this code. Its showing error. Please help me out. Thanks!
Here S_ID is the data which I would like to search from table & ID is the primary key in the EDO Table.
In this case you may detect if the recordset is empty checking .EOF property:
Sub TestIfRecordFound()
Dim strConnection As String
Dim strID As String
Dim strQuery As String
Dim objConnection As Object
Dim objRecordSet As Object
strConnection = _
"Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source='C:\ceo.accdb';"
strID = Sheets("My").Range("A1").Value
strQuery = _
"SELECT * FROM EDO WHERE ID = '" & strID & "';"
Set objConnection = CreateObject("ADODB.Connection")
objConnection.Open strConnection
Set objRecordSet = objConnection.Execute(strQuery)
If objRecordSet.EOF Then
MsgBox "Record Not found"
Else
MsgBox "Record Found"
End If
objConnection.Close
End Sub
If Id is numeric than the sql should be:
StrSql = "SELECT * FROM EDO WHERE Id = " & S_ID
You also did not define S_ID, so it will be handle as a variant here. If you still get an error, you might have to make it "& CStr(S_ID)".

How to run a SQL Query from Excel in VBA on changing a Dropdown

I'm trying to create a dropdown that upon changing the selection from the list of options will run a query that will insert the query results into the page. Here's what I have thus far:
Sub DropDown1_Change()
Dim dbConnect As String
Dim leagueCode As String
Dim leagueList As Range
Dim leagueVal As String
Dim TeamData As String
Set leagueList = Worksheets("Menu Choices").Range("A5:A10")
Set leagueVal = Worksheets("Menu Choices").Cell("B1").Value
leagueCode = Application.WorksheetFunction.Index(leagueList, leagueVal)
TeamData = "SELECT DISTINCT(Teams.teamID), name FROM Teams WHERE lgID = '" & leagueCode & "' & ORDER BY name ASC"
With Worksheets("Menu Choices").QueryTables.Add(Connection:=dbConnect, Destination:=Worksheets("Menu Choices").Range("D5"))
.CommandText = TeamData
.Name = "Team List Query"
.Refresh BackgroundQuery:=False
End With
End Sub
Anywho have any suggestions to get it working? Thanks in advance!
I was able to resolve the issue using similar code to the following:
Sub createTeamList()
Dim cn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim SQL As String
Dim inc As Integer
Dim topCell As Range
Dim leagueID As String
Dim leagueList As Range
Dim leagueChoice As Range
Set leagueList = Worksheets("Menu Choices").Range("A4:A9")
Set leagueChoice = Worksheets("Menu Choices").Range("B1")
leagueID = Application.WorksheetFunction.Index(leagueList, leagueChoice)
Set topCell = Worksheets("Menu Choices").Range("D4")
With topCell
Range(.Offset(1, 0), .Offset(0, 1).End(xlDown)).ClearContents
End With
With cn
.ConnectionString = "Data Source=" & ThisWorkbook.Path & "\lahman_57.mdb"
.Provider = "Microsoft Jet 4.0 OLE DB Provider"
.Open
End With
inc = 0
SQL = "SELECT teamID, name " _
& "FROM Teams " _
& "WHERE lgID = '" & leagueID & "' " _
& "GROUP BY teamID, name " _
& "ORDER BY name "
rs.Open SQL, cn
With rs
Do Until .EOF
topCell.Offset(inc, 0) = .Fields("teamID")
topCell.Offset(inc, 1) = .Fields("name")
inc = inc + 1
.MoveNext
Loop
End With
rs.Close
cn.Close
End Sub