使用 SELECT ADODB Excel 的子查询不工作 (VBA)
Subquery using SELECT ADODB Excel Not Working (VBA)
我正在尝试使用 ADODB Excel 中的子查询 select 来自其他 table 的数据。这是我的代码:
Sub CopyData()
Dim cmd As String
If OpenConnection() = True Then 'The connection function already created in my module
cmd = "SELECT * FROM (SELECT [SheetName] FROM `Breakdown structure library$` WHERE [Name (Name *)]='WBS');"
Rcdset.Open cmd, Con, adOpenStatic, adLockBatchOptimistic
With shTemp
.Cells.Delete
.Range("A1").CopyFromRecordset Rcdset
End With
If Con.State Then Con.Close
End If
End Sub
结果错误:
Run-time error '-2147217904' (80040e10): No value given for one or more parameters
我知道发生了什么。您必须在 sheet 名称末尾添加“$”才能在 ADODB Excel 中执行查询,例如:
SELECT * FROM `MyTable` '(not working in ADODB Excel, but working in Access database)
SELECT * FROM `MyTable$` '(working in ADODB Excel)
我不知道如何创建 sql 子查询来自动识别 table,我们要从那里 select 数据。
您不能使用子 select 来确定 select 的 table 名称,请使用 2 个查询。
Dim sTableName As String, SQL As String, rcdset As New ADODB.Recordset
If OpenConnection() = True Then 'The connection function already created in my module
SQL = " SELECT [SheetName] " & _
" FROM `Breakdown structure library$` " & _
" WHERE [Name (Name *)]='WBS';"
sTableName = con.Execute(SQL)(0)
SQL = " SELECT * FROM [" & sTableName & "$]"
rcdset.Open SQL, con, adOpenStatic, adLockBatchOptimistic
With shTemp
.Cells.Delete
.Range("A1").CopyFromRecordset rcdset
End With
If con.State Then con.Close
End If
我正在尝试使用 ADODB Excel 中的子查询 select 来自其他 table 的数据。这是我的代码:
Sub CopyData()
Dim cmd As String
If OpenConnection() = True Then 'The connection function already created in my module
cmd = "SELECT * FROM (SELECT [SheetName] FROM `Breakdown structure library$` WHERE [Name (Name *)]='WBS');"
Rcdset.Open cmd, Con, adOpenStatic, adLockBatchOptimistic
With shTemp
.Cells.Delete
.Range("A1").CopyFromRecordset Rcdset
End With
If Con.State Then Con.Close
End If
End Sub
结果错误:
Run-time error '-2147217904' (80040e10): No value given for one or more parameters
我知道发生了什么。您必须在 sheet 名称末尾添加“$”才能在 ADODB Excel 中执行查询,例如:
SELECT * FROM `MyTable` '(not working in ADODB Excel, but working in Access database)
SELECT * FROM `MyTable$` '(working in ADODB Excel)
我不知道如何创建 sql 子查询来自动识别 table,我们要从那里 select 数据。
您不能使用子 select 来确定 select 的 table 名称,请使用 2 个查询。
Dim sTableName As String, SQL As String, rcdset As New ADODB.Recordset
If OpenConnection() = True Then 'The connection function already created in my module
SQL = " SELECT [SheetName] " & _
" FROM `Breakdown structure library$` " & _
" WHERE [Name (Name *)]='WBS';"
sTableName = con.Execute(SQL)(0)
SQL = " SELECT * FROM [" & sTableName & "$]"
rcdset.Open SQL, con, adOpenStatic, adLockBatchOptimistic
With shTemp
.Cells.Delete
.Range("A1").CopyFromRecordset rcdset
End With
If con.State Then con.Close
End If