Inner Join String& VBA中{1}列中的整数值

时间:2017-11-03 11:44:39

标签: sql excel-vba ado vba excel

请查看我的下表和VBA代码。

表1: -

enter image description here

表2: -

enter image description here

所需输出

enter image description here

我得到表达式中的类型不匹配。错误,我认为这是因为在表2中字符串&整数值都可用。

请查看我的以下VBA代码并指导我如何执行内部联接。

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

1 个答案:

答案 0 :(得分:0)

更改sql查询以确保将Sr比较为字符串

sql_string = "SELECT [Sheet1$].[Sr], [Sheet3$].[Names] FROM [Sheet3$] INNER JOIN [Sheet1$] ON CStr([Sheet1$].[Sr])=CStr([Sheet3$].[Sr])"