我有一个Excel电子表格,正在尝试对其执行SQL查询。我得到“没有给一个或多个必需参数任何值”,所以我认为这是我的查询问题。我可以执行类似“ SELECT * FROM [Employee $ A2:A4]”的查询,但是当我使用名称(即名称,标题...等,甚至使用诸如F1的通用列引用)引用特定列时,得到“没有为一个或多个必需参数提供值”。
这是我的代码:
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 = "SELECT Employee FROM [Employee$] AS e WHERE e.Skill_Title = " & """" & skillTitle & """" & " AND e.Branch = " & """" & branchTitle & """" & " AND e.Skill_Prof = 5"
rs.Open strSQL, cn
MsgBox (rs.GetString)
有什么想法吗?
答案 0 :(得分:1)
尝试应用以下示例。
如果问题仍然存在并且您正在使用输入内容,请告诉我。
我在员工表上有这个
按如下所示创建“ MyQuery”子流程(如您所见,这是代码的副本,有一些区别):
Sub MyQuery(ByVal skillTitle As String, _
ByVal branchTitle As String, _
ByVal skillProf As Integer)
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 = _
"SELECT Employee " & _
"FROM [Employee$] AS e " & _
"WHERE e.Skill_Title = '" & skillTitle & "' AND " & _
"e.Branch = '" & branchTitle & "' AND " & _
"e.Skill_Prof = " & CStr(skillProf)
Rs.Open strSQL, Cn
MsgBox (Rs.GetString)
'Do not forget closing your connection'
Rs.Close
Cn.Close
End Sub
进行快速测试:
Sub test()
'Try running this'
Call MyQuery("FOUR", "Y", 5)
End Sub
结果:
答案 1 :(得分:0)
您为列命名了吗?从您的代码示例中,我不确定您是已命名列还是假设列标题足以作为参考。 “命名”列与使用列标题不同。要按名称访问列,请尝试首先为该列分配名称。
发件人:How to give a name to the columns in Excel