Select SQL Statement in Excel VBA - sql

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)".

Related

Running a SQL query in excel usin VBA

I am trying to create a macro that pulls data from a user-chosen workbook.
What I need is: 1) prompt user to choose which file they want to use 2) [Assuming a "Data" sheet always exists and has the same format] select * from Data worksheet where a condition is met 3) Output this in my excel file
My code is
Sub ConnectionToExcel()
Dim rstResult As ADODB.Recordset
Dim strConnectin As String
Dim strPath As String
Dim strSQL As String
strPath = Application.GetOpenFilename
strConnectin = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source='" & strPath & "';Extended Properties=""Excel 12.0 XML;HDR=YES;IMEX=0"" "
Debug.Print strConnectin
strSQL = "SELECT * FROM [Data$] "
Set rstResult = New ADODB.Recordset
rstResult.Open strSQL, strConnectin
'adOpenForwardOnly , adLockReadOnly, adCmdText
Sheets("Export").Range("A2").CopyFromRecordset rstResult
End Sub
I am not sure how to add the condition in the select statement. The condition would be to select the items based on a given value in one of the cols. So for example, Select * from table where Product=Banana"
ID Product
14243 Apple
43543 Banana
43432 Banana
Thanks
I tried a couple of if statements,
if worksheets(Data).range("A1:A220000")="Condition" then
strSQL = "SELECT * FROM [Data$] "
end if
I also tried adding a where clause in the select statement but doesn't seem to work either
You can try this, using Data$.Product='Banana' as WHERE clause.
Sub ConnectionToExcel()
Dim rstResult As ADODB.Recordset
Dim strConnectin As String
Dim strPath As String
Dim strSQL As String
strPath = Application.GetOpenFilename
strConnectin = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source='" & strPath & "';Extended Properties=""Excel 12.0 XML;HDR=YES;IMEX=0"" "
Debug.Print strConnectin
strSQL = "SELECT * FROM [Data$] WHERE (Data$.Product='Banana')"
Set rstResult = New ADODB.Recordset
rstResult.Open strSQL, strConnectin
'adOpenForwardOnly , adLockReadOnly, adCmdText
Sheets("Export").Range("A2").CopyFromRecordset rstResult
End Sub

Missing data partially importing filtered text file data through sql with excel vba

I would like to import a 30Mb text file into excel filtering just what I want.
I have tried with small files and I see that some columns with byte data shows problems. I see a black sell or wrong values.
I tried different provider for the connection but I loose always data.
text_2.txt:
946737293;98FECB80;FF;FF;0;0;0;0;FF;FF
946737293;98EAFFFE;0;EE;0;0;0;0;FF;FF
946737294;98FE0F82;65;6E;4F;0;0;0;FF;FF
946737295;8CFD0282;FF;FF;FF;FF;FF;FF;0;FD
946737295;9CE78280;FF;1;5;FF;FF;FF;FF;FF
946737295;9CE78280;C0;FF;0;0;0;0;FF;FF
946737296;8CFD0282;FF;FF;FF;FF;FF;FF;0;FD
excel result
Sub FilterFile2()
Dim log_path As String
Dim log_file As String
Dim objConnection As ADODB.Connection 'Object
Dim objRecSet As ADODB.Recordset 'Object
Dim strConnection As String
Dim strSql As String
Dim strPath As String
Dim strTable As String
Dim ws As Variant
strPath = "I:\Codici\Excel\filtra_file_testo"
strTable = "test_2.txt"
strConnection = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & strPath & ";Extended Properties='Text;HDR=NO;IMEX=1'"
' SAME PROBLEM
'strConnection = "Driver={Microsoft Text Driver (*.txt; *.csv)};" & _
' "Dbq=" & strPath & ";Extensions=asc,csv,tab,txt;" 'HDR=NO;Persist Security Info=False"
'https://www.exceltip.com/import-and-export-in-vba/import-data-from-a-text-file-ado-using-vba-in-microsoft-excel.html
' SAME PROBLEM
'strConnection = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
'"Data Source=" & strPath & ";Extended Properties='Text;HDR=NO;IMEX=1'"
'ADOX doesn't read the data, you still use ADODB for that.
Set objConnection = CreateObject("ADODB.Connection")
objConnection.Open strConnection
strSql = "SELECT * " & _
" FROM " & strTable & _
" WHERE F3='FF'"
'" WHERE F2='9CE78280'" 'the same problem
Debug.Print strSql
Set objRecSet = New ADODB.Recordset
objRecSet.Open strSql, objConnection, adOpenForwardOnly, adLockReadOnly, adCmdText
'Set objRecSet = objConnection.Execute(strSql)
If objRecSet.State <> adStateOpen Then
objConnection.Close
Set objConnection = Nothing
Exit Sub
End If
'Copy Data to Excel'
Set ws = ActiveSheet
''ActiveCell.CopyFromRecordset objRecSet
ws.Cells(12, 2).CopyFromRecordset objRecSet 'write new data 'colonna 5 e 6 non corrette
objRecSet.Close
objConnection.Close
End Sub

VBA Excel SQL object variable or with block variable not set

Hi I keep getting an error when trying to upload to sql. The code have been working before, but I can find what I missed when rewriting the code..
it is falling at line:
cmd.CommandText = strSQL
the code is pretty simple it takes one column in a sheet and then upload or insert it in to an SQL database. please tell me what code I'm missing, or if I declare something wrong here
Dim cn As ADODB.Connection
Set sTroksheet = ThisWorkbook.Sheets("Mlist")
Set cn = New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim strConn As String
Dim SQLstr As String
Dim SQLstrl As String
Dim Password As String
Dim Server_Name As String
Dim User_ID As String
Dim Database_Name As String
Dim Port_Name As String
Dim strTable As String
Dim excel_row As Long
Dim cmd As ADODB.Command
Dim rst_recordset As ADODB.Recordset
If ThisWorkbook.Sheets("Tournament Settings").Range("D4") = vbNullString
Then
MsgBox "Please setup database connection first in (DB Setup) in top menu"
Exit Sub
Else
Server_Name = Sheets("Software_Setup").Range("c3").Value
Database_Name = Sheets("Software_Setup").Range("c4").Value
User_ID = Sheets("Software_Setup").Range("c5").Value 'id user or username
Password = Sheets("Software_Setup").Range("c6").Value 'Password
Port_Name = Sheets("Software_Setup").Range("c7").Value 'Password
strConn = "Driver={MySQL ODBC 5.3 ANSI Driver};Server=" & _
Server_Name & ";Database=" & Database_Name & _
";Uid=" & User_ID & ";Pwd=" & Password & ";"
cn.Open strConn
LastRow = sTroksheet.Range("A65536").End(xlUp).row
strTable = Database_Name & ".TLHMember_List"
strSQL = "INSERT INTO " & strTable & _
" (Player) VALUES "
strSQL2 = ""
For excel_row = 1 To LastRow
strSQL2 = strSQL2 & _
"('" & sTroksheet.Cells(excel_row, 1) & "') ,"
Next excel_row
strSQL = strSQL & strSQL2
Mid(strSQL, Len(strSQL), 1) = ";" ' gets rid of the last comma
cmd.CommandText = strSQL
cmd.Execute
cn.Close
End If
You need to either change this line:
Dim cmd As ADODB.Command
to
Dim cmd As New ADODB.Command
or just before error line add new line:
Set cmd = new ADODB.Command
cmd.CommandText = strSQL

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

Using a boolean function after where (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