无效使用Null VBA Excel

时间:2017-11-03 06:09:27

标签: mysql vba excel-vba adodb excel

请查看下表和代码。我正面临无效使用空错误

表1

enter image description here

表2

enter image description here

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

请指导我..我的错误。

enter image description here

#2> 之后的 table2列中,有一些数字与 table1列Sr 数字类似。我想要进行内连接根据该特定数字。

所需的输出。

enter image description here

1 个答案:

答案 0 :(得分:0)

首先在模块顶部写Option ExplicitWhy 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,看看你得到了什么。
  • 找一种方法来测试你得到的东西