如果有人帮忙的话会很棒。
我想从单独的工作表中提供单元格引用作为参数在哪里查询我的意思而不是字符串" Arunraj S",我需要从范围中提供参考(" c3&#第1页的34;)(" PDA")。
在通过查询提供直接字符串的同时检索罚款。
但是当我尝试更改下面的查询时,它会抛出语法错误;
query = "SELECT DISTINCT [Client Name] FROM [Execution Report$] WHERE
[Employee Name] =" & Sheets("PDA").Range(C3).value
这是我的代码:
Sub Pull_Data_from_Excel_with_ADODB()
Dim cnStr As String
Dim rs As ADODB.Recordset
Dim query As String
Dim fileName As String
fileName = "C:\Users\nizamudeen.s\Desktop\PDA Template.xlsx"
cnStr = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & fileName & ";" & _
"Extended Properties=Excel 12.0"
query = "SELECT DISTINCT [Client Name] FROM [Execution Report$] WHERE [Employee Name] = 'Arunraj S';"
Set rs = New ADODB.Recordset
rs.Open query, cnStr, adOpenUnspecified, adLockUnspecified
Cells.Clear
Range("A2").CopyFromRecordset rs
Dim cell As Range, i As Long
With Range("A1").CurrentRegion
For i = 0 To rs.Fields.Count - 1
.Cells(1, i + 1).Value = rs.Fields(i).Name
Next i
.EntireColumn.AutoFit
End With
End Sub
答案 0 :(得分:0)
通常,员工的姓名是文本字符串。您应该能够将单引号(又名' ticks')与包含在整个SQL语句中的双引号结合起来,以便您不必处理引号字符串中的引号。
example.GetPerfectAttributeIndex< Specialized1, int >( 1, &Specialized1::GetCount );
在表格中使用 Bob (&#34; PDA&#34;)。范围(C3),这应该是,
query = "SELECT DISTINCT [Client Name] FROM [Execution Report$] WHERE [Employee Name] LIKE '" & Sheets("PDA").Range(C3).value & "';"
我通常&#39;模式匹配&#39;使用LIKE运算符但是出于所有意图和目的,LIKE与equals相同。
答案 1 :(得分:0)
您将查询作为字符串传递。现在看来,您的查询看起来像这样(假设单元格C3中的名称为Tom Smith
:
SELECT DISTINCT [Client Name] FROM [Execution Report$] WHERE
[Employee Name] = Tom Smith
看一下,你可能会发现它会在SQL中失败,因为它应该读取(注意名称周围的单引号):
SELECT DISTINCT [Client Name] FROM [Execution Report$] WHERE
[Employee Name] = 'Tom Smith'
因此,请将query
声明更改为:
query = "SELECT DISTINCT [Client Name] FROM [Execution Report$] WHERE
[Employee Name] ='" & Sheets("PDA").Range(C3).value & "'"
这样可以解决问题吗?