【问题标题】:Excel vba - ADO inner join on data tablesExcel vba - 数据表上的 ADO 内连接
【发布时间】:2014-09-20 01:18:50
【问题描述】:

我在 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

结束函数

【问题讨论】:

  • 你能发布完整的代码吗?
  • “没有为一个或多个必需参数提供值”的一个非常常见的原因是语法错误,特别是字段名称。检查您使用的字段名称是否正确。
  • 上传完整代码,rs.Open方法出现错误

标签: vba excel ado


【解决方案1】:

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

vLookup 本质上是一个表连接。如果您愿意,您甚至可以将它与 Application.WorksheetFunctions 一起使用。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-08
    • 1970-01-01
    • 2019-01-10
    • 2020-10-29
    • 2013-06-10
    • 1970-01-01
    相关资源
    最近更新 更多