Excel vba – 数据表上的ADO内联接

我在Excel中有两个数据表,我希望在我的vba代码中join一个数据表。 我已经将ADO连接器标识为执行此操作的最佳方法,但是使用下面的查询,我得到以下错误

“运行时错误-2147217904

没有给出一个或多个所需参数的值“

SELECT components.[name], InputData.Datatype FROM [Rules$A5:F30] components INNER JOIN [Rules$O5:R17] InputData ON components.[name] = InputData.[name] WHERE components.RowId = 0 GROUP BY components.[name], InputData.Datatype 

编辑:完整的代码:

 Dim cn As ADODB.Connection Dim rs As ADODB.Recordset Dim dataRows As Integer 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 = "SELECT components.[name], InputData.Datatype " _ + " FROM [" + GetTableAddress("componentTable") _ + "] components INNER JOIN [" + GetTableAddress("DataLocations") + "] InputData" _ + " ON components.[name] = InputData.[name] " _ + " WHERE components.RowId = " + CStr(RowId) + " GROUP BY components.[name], InputData.Datatype" rs.Open strsql, cn If Not rs.EOF Then dataRows = rs.GetRows 

和GetTableAddress函数

 Private Function GetTableAddress(tableName) Dim oSh As Worksheet Dim oLo As ListObject For Each oSh In ThisWorkbook.Worksheets For Each oLo In oSh.ListObjects If oLo.Name = tableName Then GetTableAddress = Replace(oSh.ListObjects(tableName).Range.AddressLocal, "$", "") GetTableAddress = oSh.Name + "$" + GetTableAddress End If Next Next 

结束function

如果两个数据集都在Excel中,则应使用vLookup创build最终表。 这对你来说会更容易,好处是你可以使用你已经熟悉的语法。

vLookup本质上是一个表连接。 你甚至可以在Application.WorksheetFunctions使用它,如果你想这样做的话。

此外, RecordSet.GetRows可以返回一个数组。 如果您不希望返回多个值,则应该使用CInt(rs.GetString)