在SQL查询中使用单元格引用
问题描述:
我正在使用下面的VBA命令通过使用单元格引用作为过滤器使用SQL查询提取数据。在SQL查询中使用单元格引用
Public Sub Run()
Dim SQL As String
Dim Connected As Boolean
Dim server_name As String
Dim database_name As String
Dim Allocation As String
Sheets("Perc").Select
Range("A6").Select
Selection.CurrentRegion.Select
Selection.ClearContents
' Our query
SQL = "SELECT Segmentation_ID,MPG,SUM(Segmentation_Percent) AS PERC " & _
"FROM dbo.HFM_ALLOCATION_RATIO " & _
"WHERE Segmentation_ID = " & Sheets("Perc").Range("A1").Value & " " & _
"GROUP BY Segmentation_ID,MPG ORDER BY MPG"
' Connect to the database
server_name = Sheets("General").Range("D1").Value
database_name = Sheets("General").Range("G1").Value
Connected = Connect(server_name, database_name)
If Connected Then
' If connected run query and disconnect
Call Query(SQL)
Call Disconnect
Else
' Couldn't connect
MsgBox "Could Not Connect!"
End If
End Sub
但是当我运行宏,它显示一个运行时错误
无效的列名ALO0000274
这里ALO0000274
是我在A1
设置的过滤器。
请帮助解决此错误。
答
添加引号您where
条款(你传递一个文本值,所以你需要包括引号):
SQL = "SELECT Segmentation_ID,MPG,SUM(Segmentation_Percent) AS PERC " & _
"FROM dbo.HFM_ALLOCATION_RATIO " & _
"WHERE Segmentation_ID = '" & Sheets("Perc").Range("A1").Value & "' " & _
"GROUP BY Segmentation_ID,MPG ORDER BY MPG"
(注意单引号'
围住要过滤的值)
答
我没有看到你在你的字符串周围添加单引号。您是否尝试过将您的SQL语句的WHERE子句部分更改为"WHERE Segmentation_ID = '" & Sheets("Perc").Range("A1").Value & "' "
+0
谢谢单引号是问题... – 2014-10-20 18:37:15
谢谢我在我的过滤器中错过了单引号......我设置了引号,并得到结果... – 2014-10-20 18:36:53
请注意那些单引号不是' t数值所必需的... – 2014-10-20 21:38:25
@ n8。问题中提供的示例是一个字符串,因此需要引号*。当然,您可以检查该值是代码中的字符串还是数字,并在需要时包含/排除引号 – Barranka 2014-10-20 21:44:49