在SQL查询中使用单元格引用

我正在使用下面的VBA命令通过使用单元格引用作为filter使用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 

但是,当我运行macros,它显示一个运行时错误

无效的列名称ALO0000274

这里ALO0000274是我在A1设置的filter。

请帮助解决这个错误。

加引号到你的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" 

(注意包含你想要过滤的值的单引号)

我没有看到你在你的string附加你的单引号。 您是否尝试将SQL语句的WHERE子句部分更改为"WHERE Segmentation_ID = '" & Sheets("Perc").Range("A1").Value & "' "