How to LOAD data from recordset into separate columns? - sql

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])

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

Excel VBA SQL multi JOIN, Multi file types

I've looked for awhile now and have found some useful tips for formatting but I still can't get my code to work. It works when I remove the second JOIN but gives a Parameter error with the second JOIN added.
My code is:
Sub MultiJoinQuery()
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim csvPath As String
Dim xlsxPath As String
Dim con As String
Dim strSQL As String
Dim i As Long
Set cn = New ADODB.Connection
Set rs = New ADODB.Recordset
csvPath = "C:\Users\Me\"
xlsxPath = "C:\Users\Somewhere Else\Book1.xlsx"
con = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & xlsxPath & ";Extended Properties=""Excel 12.0 Xml;HDR=Yes;"";"
strSQL = "SELECT * " _
& "FROM ([Sheet1$] a " _
& "LEFT JOIN [Text;FMT=Delimited;HDR=Yes;DATABASE=" & csvPath & "].users.csv b ON a.[Name]=b.[full_name]) " _
& "LEFT JOIN [Text;FMT=Delimited;HDR=Yes;DATABASE=" & csvPath & "].enrollments.csv c ON c.[user_id]=b.[user_id] "
rs.Open strSQL, con, 3, 3
For i = 0 To rs.Fields.Count - 1
Cells(1, i + 1).value = rs.Fields(i).Name
Next
Range("A2").CopyFromRecordset rs
''Tidy up
rs.Close
Set rs = Nothing
cn.Close
Set cn = Nothing
End Sub
With parentheses I get
Without parentheses, I get
Why do I keep getting a Param error? How can I make this code work?
Your help is appreciated.

SQL ADODB Recordset select distinct is in alphabetical order

I'm using an ADODB record set in VBA. When I use Select Distinct in a SQL query of the ADODB record set the results come out in alphabetical order. I need the results in the order they are in the data. Is that possible?
Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
DatPath = ThisWorkbook.Path & "\Temp\" & TB.Name
strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & DatPath & ";Extended Properties=""Excel 8.0;HDR=Yes;IMEX=1"";"
cn.Open strCon
strSQL = "SELECT Distinct(Period) from [Data$] "
rs.Open strSQL, cn, 3, 3
ThisWorkbook.Sheets("ADO Out").Cells.Clear
ThisWorkbook.Sheets("ADO Out").Activate
ThisWorkbook.Sheets("ADO Out").Cells(1, 1).CopyFromRecordset rs
Here are two workarounds that both involve retrieving all Period records.
Range.RemoveDuplicates will remove the duplicates while preserving the order
Sub UnorderedPeriod()
Dim DatPath As String, strCon As String, strSQL As String
Dim cn As Object, rs As Object
Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
DatPath = ThisWorkbook.Path & "\Temp\" & TB.Name
strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & DatPath & ";Extended Properties=""Excel 8.0;HDR=Yes;IMEX=1"";"
cn.Open strCon
strSQL = "SELECT [Period] from [Data$]"
rs.Open strSQL, cn, 3, 3
With ThisWorkbook.Sheets("ADO Out")
.Cells.Clear
.Cells(1, 1).CopyFromRecordset rs
.Activate
.Columns(1).RemoveDuplicates Columns:=1
End With
End Sub
Use an ArrayList to remove the duplicates
Function CopyDistinctFromRecordset(rs As Object, Target As Range)
Dim list As Object
Dim data
Dim x As Long
rs.MoveFirst
data = rs.getRows
Set list = CreateObject("System.Collections.ArrayList")
For x = 0 To UBound(data, 2)
If Not list.Contains(data(0, x)) Then list.Add data(0, x)
Next
Target.Resize(list.Count).Value = Application.Transpose(list.ToArray)
End Function

Copying ADO recordset into excel worksheet

I'm trying to open a CSV file and query it and return the results into column A of the second worksheet of "ThisWorkbook".
I'm not getting any errors so I do not see why it is not copying the record set into excel.
Dim con As ADODB.Connection
Dim rs As ADODB.Recordset
Set con = New ADODB.Connection
Set rs = New ADODB.Recordset
Dim currentDataFilePath As String
Dim currentDataFileName As String
Dim nextRow As Integer
currentDataFilePath = "C:\Users\M\folder\"
currentDataFileName = "csv-file"
con.Open "Provider=Microsoft.JET.OLEDB.4.0;" & _
"Data Source=" & currentDataFilePath & ";" & _
"Extended Properties=""text;HDR=NO;FMT=Delimited;IMEX=1"""
'rs.ActiveConnection = con
rs.Open "SELECT Name FROM [" & currentDataFileName & ".csv] WHERE Datatype ='TYPE3'",
con
ThisWorkbook.Worksheets("Sheet2").Range("A:A").CopyFromRecordset rs
rs.Close
con.Close
Set rs = Nothing
Set con = Nothing
End Sub
You might refer to the CopyFromRecordset() method.
Based on your code above, after the rs.Open command you would add something like this:
ActiveWorksheet.Range("A1").CopyFromRecordset rs
See more here: http://msdn.microsoft.com/en-us/library/office/ff839240%28v=office.15%29.aspx

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