Running a SQL query in excel usin VBA - sql

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

Related

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

Where oh Where (VBA SQL Where Clause with Variable)

I am SQL guy trying to help with a VBA project. I get a VBA error when I try to run this sql statement. Run-time error '-2147217913 (80040e07)' Automation error.
I can send a number without issue so I know I am doing something wrong when a string is passed. Thank you for your help! I have spent so much time trying to figure it out.
sSQLSting = "SELECT TOP 10 PctTtlAssets, Port_Code FROM [db_detail$]
WHERE Port_Code = ' " & [vbaThisPort] & " ' "
which looks like this when saved to my variable.
sSQLSting = "SELECT TOP 10 PctTtlAssets, Port_Code FROM [db_detail$]
WHERE Port_Code = 'salmemhs' "
Thank you
PS
Here is the full code the vba guy is using. Again, works fine until I send a string.
Sub sbADO()
Dim sSQLQry As String
Dim ReturnArray
Dim Conn As New ADODB.Connection
Dim mrs As New ADODB.Recordset
Dim DBPath As String, sconnect As String, vbaThisPort As String
vbaThisPort = Trim(ThisWorkbook.Names("ThisPort").RefersToRange(1, 1))
'MsgBox (vbaThisPort) 'Testing
DBPath = ThisWorkbook.FullName
'You can provide the full path of your external file as shown below
'DBPath ="C:\InputData.xlsx"
sconnect = "Provider=MSDASQL.1;DSN=Excel Files;DBQ=" & DBPath & ";HDR=Yes';"
' Your SQL Statemnt (Table Name= Sheet Name=[DataSheet$])"
Conn.Open sconnect
sSQLSting = "SELECT TOP 10 PctTtlAssets, Port_Code FROM [db_detail$] WHERE Port_Code = '" & [vbaThisPort] & "'"
mrs.Open sSQLSting, Conn
'=>Load the Data into an array
'ReturnArray = mrs.GetRows
''OR''
'=>Paste the data into a sheet
ActiveSheet.Range("A2").CopyFromRecordset mrs
'Close Recordset
mrs.Close
'Close Connection
Conn.Close
End Sub

VBA, Import CSV split by ";" to sheet

I am trying to import a CSV file split by semicolon ";" into an excel object so I can use it later on.
Ideally i would like to use ADO, DAO or ADODB so I can also run SQL queries on the object, and get sum of specific fields, or total number of fields and so on.
So far i've gotten the code below, but it does not split the data by ";", so it all comes back as 1 field instead of multiple fields that can be handled.
Sub Import()
Dim conn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim f As ADODB.Field
Dim csvName, csvPath
csvPath = ActiveWorkbook.path
csvName = "fileName.csv"
conn.Open "DRIVER={Microsoft Text Driver (*.txt; *.csv)};DBQ=" & csvPath & ";"
rs.Open "SELECT * FROM " & csvName, conn, adOpenStatic, adLockReadOnly, adCmdText
Debug.Print rs.Fields
While Not rs.EOF
For Each f In rs.Fields
Debug.Print f.Name & "=" & f.Value
Next
Wend
End Sub
Can anyone give me an idea how I can also split the data by ";" and query it using SQL query? Or a different object that I could load a CSV into and query certain columns.
Here's example:
Public Sub QueryTextFile()
Dim rsData As ADODB.Recordset
Dim sConnect As String
Dim sSQL As String
' Create the connection string.
sConnect = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=C:\Files\;" & _
"Extended Properties=Text;"
' Create the SQL statement.
sSQL = "SELECT * FROM Sales.csv;"
Set rsData = New ADODB.Recordset
rsData.Open sSQL, sConnect, adOpenForwardOnly, _
adLockReadOnly, adCmdText
' Check to make sure we received data.
If Not rsData.EOF Then
' Dump the returned data onto Sheet1.
Sheet1.Range("A1").CopyFromRecordset rsData
Else
MsgBox "No records returned.", vbCritical
End If
' Clean up our Recordset object.
rsData.Close
Set rsData = Nothing
End Sub
The only answer I found that was usable was to create an ini file in the current folder, and enter the delimiter in the ini file.
iniPath = activeworkbook.path & "\"
iniName = "schema.ini"
iniPathName = iniPath & iniName
If Not fso.FileExists(iniPathName) Then
fso.CreateTextFile (iniPathName)
End if

How to LOAD data from recordset into separate columns?

I have created a macro which search for all employees who were on trainings this year.
I'm weak in SQL and I need somebodys help.
Currently my macro works like this that it creates 3 column in Excel and loads in it all the data
Name||First Name||TrainingName
Employee1.Name||Employee1.FirstName||TrainingName1
Employee1.Name||Employee1.FirstName||TrainingName2
Employee2.Name||Employee2.FirstName||TrainingName1
Employee3.Name||Employee3.FirstName||TrainingName1
I want that the data will be showed like this:
Name||First Name||TrainingName1||TrainingName2 etc..
Employee1.Name||Employee1.FirstName||TrainingName1||TrainingName2 etc..
How to change the SQL line to get what I want.
Sub TRaining()
Dim con As ADODB.connection
Dim rs As ADODB.Recordset
Dim path1 As String, SQLstr As String, conString As String, i
With Application.FileDialog(msoFileDialogFilePicker)
.Title = "GDZIE JEST PLIK?"
.Show
path1 = .SelectedItems(.SelectedItems.Count)
End With
Set con = New ADODB.connection
conString = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & path1 & ";" & _
"Extended Properties=Excel 12.0"
con.Open conString
SQLstr = "SELECT o.[Last Name] AS [LastName], o.[First Name] AS [FirstName], s.[TRAINING] AS [T0] FROM [pracownicy$] o LEFT JOIN [szkolenia$] s ON s.[GUID]=o.[GUID] WHERE s.[GUID] IS NOT NULL"
Set rs = New ADODB.Recordset
rs.Open SQLstr, con, adOpenUnspecified, adLockUnspecified
With ThisWorkbook.ActiveSheet
For i = 0 To rs.Fields.Count - 1
ActiveSheet.Cells(1, i + 1).Value = rs.Fields(i).Name
Next i
Range("A2").CopyFromRecordset rs
End With
End Sub
Thank you for your help!
Hi check this once i have some quires for you
INSERT INTO [TABLE]([Name, First Name, Training],[Employee1,Employee1,Training1],[Employee1,Employee1,Training 2],[Employee2,Employee 2,Training1],[Employee3,Employee 3,Training1])VALUES(#[Name, FirstName,Training] ,#[Employee1,Employee1,Training1] ,#[Employee1,Employee1,Training 2] ,#[Employee2,Employee 2,Training1] ,#[Employee3,Employee 3,Training1])

Query Excel worksheet in MS-Access VBA (using ADODB recordset)

I'd like to query an Excel worksheet in VBA and specify conditions.
The simple query "SELECT * FROM [PCR$]" works perfectly, but I don't know how to add a WHERE clause.
I tried cmd2.CommandText = "SELECT * FROM [PCR$] WHERE ([B1] IS NOT NULL)" but then it complains about missing parameters.
This is the complete code:
Dim rs2 As New ADODB.Recordset
Dim cnn2 As New ADODB.Connection
Dim cmd2 As New ADODB.Command
Dim intField As Integer
Dim strFile As String
strFile = fncOpenFile
If strFile = "" Then Exit Sub
With cnn2
.Provider = "Microsoft.Jet.OLEDB.4.0"
.ConnectionString = "Data Source='" & strFile & "'; " & "Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'"
.Open
End With
Set cmd2.ActiveConnection = cnn2
cmd2.CommandType = adCmdText
cmd2.CommandText = "SELECT * FROM [PCR$]"
rs2.CursorLocation = adUseClient
rs2.CursorType = adOpenDynamic
rs2.LockType = adLockOptimistic
rs2.Open cmd2
In your connection string you say
Excel 8.0;HDR=Yes
Which means that the first row will be treated as the header, no matter what it contains. If you want to use F1, F2 etc, say
Excel 8.0;HDR=No
Because you have the HDR=Yes option, the column name should be the data in the first row.
http://support.microsoft.com/kb/316934