我在excel中有两个数据表,我希望在我的vba代码中加入一个集合。我已经确定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
结束功能
答案 0 :(得分:1)
如果两个数据集都在Excel中,则应使用vLookup
创建最终表。它对您来说更容易,而且好处是您可以使用您已经熟悉的语法。
vLookup
本质上是一个表连接。如果您希望以这种方式进行,您甚至可以将其与Application.WorksheetFunctions
一起使用。
此外,RecordSet.GetRows
可以返回一个数组。如果您不希望返回多个值,则应该使用CInt(rs.GetString)
。