请查看下表和代码。我正面临无效使用空错误
表1
表2
VBA代码: -
Sub sql()
sql_string = "Select [Sheet1$].[Sr], [Sheet2$].[Name], [Sheet2$].[Value] From [Sheet1$]" & _
" Inner Join [Sheet2$] On CInt([Sheet1$].[Sr]) = CInt(Mid([Sheet2$].[Name],InStr(1,[Sheet2$].[Name],""#"")+1))"
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
Sheet5.Range("A21").CopyFromRecordset rs ''HERE I AM FACING ERROR
End Function
请指导我..我的错误。
在#2> 之后的 table2列中,有一些数字与 table1列Sr 数字类似。我想要进行内连接根据该特定数字。
所需的输出。
答案 0 :(得分:0)
首先在模块顶部写Option Explicit
。 Why does my code run without 'Option Explicit' but fail with it?
然后将Sub sql()
更改为以下内容:
Function sql_string() as string
sql_string = "Select [Sheet1$].[Sr], [Sheet2$].[Name], [Sheet2$].[Value] From [Sheet1$]" & _
" Inner Join [Sheet2$] On CInt([Sheet1$].[Sr]) = CInt(Mid([Sheet2$].[Name],InStr(1,[Sheet2$].[Name],""#"")+1))"
end sub
?sql_string
,看看你得到了什么。