Inner Join String & Integer Value both in 1 column in VBA - sql

Please find my below table and VBA code.
table 1:-
table 2:-
Required Output
I am getting Type Mismatch in expression. error and i think it is because in table 2 String & Integer Value both are available.
Please find my below VBA Code and guide how can i execute inner join for the same.
Sub sql()
sql_string = "SELECT [Sheet1$].[Sr], [Name],[Sheet3$].[Names] FROM" & _
"[Sheet3$] INNER JOIN [Sheet1$] ON [Sheet1$].[Sr]=[Sheet3$].[Sr]"
sq = SQL_query(sql_string)
end sub
Function SQL_query(ByRef sql_string As Variant)
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
strFile = ThisWorkbook.FullName
strCon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & strFile _
& ";Extended Properties=""Excel 12.0;HDR=Yes;IMEX=1"";"
Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
cn.Open strCon
strSQL = sql_string
rs.Open strSQL, cn ''Here i am getting error...
Sheet5.Range("A2").CopyFromRecordset rs
End Function

Change the sql query to ensure that both Sr are compared as strings
sql_string = "SELECT [Sheet1$].[Sr], [Sheet3$].[Names] FROM [Sheet3$] INNER JOIN [Sheet1$] ON CStr([Sheet1$].[Sr])=CStr([Sheet3$].[Sr])"

Related

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.

How to fix 'Automation Error' in vba when querying worksheets

I am trying to join three tables to show inventory by location for similar Items associated by "Key".
So to do that, I am joining my product list, DS, to SM which is my master list with associated products on KEY, which is an index of different product information. Finally I need to pull each one of those item's inventory information by location.
It is throwing an "Automation error" from VBA when it is trying to establish the recordset. This works when I dont have the second join in my SQL string (attaching INV table).
Private Sub CommandButton1_Click()
Dim strFile
Dim strCon
Dim strSQL
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim I
Dim SQL
strSQL = "SELECT s1.KEY, s1.Item, Loc, QOH, Total_Ship_To_WIP, Tot_Opn+pick_Units, Reserve " _
& "FROM ([SM$] AS s1 " _
& "RIGHT JOIN [DS$] AS s2 ON s1.[KEY] = s2.[KEY]) " _
& "LEFT JOIN [INV$] AS s3 ON s2.[Item] = s3.[Full_Style]"
strFile = ActiveWorkbook.FullName
strCon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & strFile _
& ";Extended Properties=""Excel 12.0;HDR=Yes;IMEX=1"";"
Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
cn.Open strCon
rs.Open strSQL, cn 'error
For I = 0 To rs.Fields.Count - 1
ActiveWorkbook.Sheets("Sheet1").Range("a10").Offset(0, I).Value = rs.Fields(I).Name
Next
ActiveWorkbook.Sheets("Sheet1").Range("a11").CopyFromRecordset rs
End Sub

Pull in Data from a SQL Table into Excel using VBA and a Data Validation Box

I have code that is pulling in data from a SQL table, and using VB and a data validation List Box that allows the user to select a criteria then it should pull in the data associated with that criteria: but I am not getting any errors and it is running the code but not pulling in any data. Can someone let me know what I am doing wrong: Here is my example: I select scenario from the Data Validation List Box and get " No Records Returned" here is my code:
Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim sConnString As String
Dim sSQL As String
Dim ceRg As Worksheet
Set ceRg = ThisWorkbook.Worksheets("RG Schedule")
If ceRg.FilterMode Then
ceRg.ShowAllData
End If
ceRg.Range("A3").ClearContents
' Create the connection string.
sConnString = "Provider=SQLOLEDB;Data Source=SQL\SQLEXPRESS;Initial Catalog=Sample;Trusted_Connection=yes;"
' Create the Connection and Recordset objects.
Set conn = New ADODB.Connection
Set rs = New ADODB.Recordset
' Open the connection and execute.
conn.Open sConnString
sSQL = "SELECT [ORDER #],[SCENARIO],[LOCATION],[FORM],[STATUS],"
sSQL = sSQL & "CAST([Date Ordered] as date),"
sSQL = sSQL & "[Design],[Cost],"
sSQL = sSQL & "CAST([Critical Obligation Date] as date),"
sSQL = sSQL & "[MGMT_APPROVED],[AUTHORIZATION_Y_N],[CUSTOMER]"
sSQL = sSQL & "FROM [dbo].[vwRG_Schedule]"
sSQL = sSQL & "WHERE [SCENARIO] = '" & Scenario & "' "
sSQL = sSQL & "ORDER BY [ORDER #]"
Set rs = conn.Execute(sSQL)
' Check we have data.
If Not rs.EOF Then
' Transfer result.
ceRg.Range("A3").CopyFromRecordset rs
' Close the recordset
rs.Close
Else
MsgBox "Error: No records returned.", vbCritical
End If
' Clean up
If CBool(conn.State And adStateOpen) Then conn.Close
Set conn = Nothing
Set rs = Nothing
End Sub

How to create and join multiple temporary tables derived from an access table in vba?

I'm in a situation where i have to create multiple temporary tables based on different sub setting conditions from an access table and do inner join to create the final table. Can you please suggest me on how to copy the information from ADO recordsets to temporary tables and perform inner join?
Here is a little sample you can start with:
Sub SQLCombineExample()
Dim con As ADODB.Connection
Dim rs As ADODB.Recordset
Set con = New ADODB.Connection
con.Open "Driver={Microsoft Excel Driver (*.xls)};" & _
"DriverId=790;" & _
"Dbq=" & ThisWorkbook.FullName & ";" & _
"DefaultDir=" & ThisWorkbook.FullName & ";ReadOnly=False;"
Set rs = New ADODB.Recordset
Set rs = con.Execute("select distinct a.test1, b.test3 from [Sheet1$] as a , [Sheet1$] as b ")
Range("f1").CopyFromRecordset rs
Set rs = Nothing
Set con = Nothing
End Sub

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