在SQL查询中使用Cell引用

时间:2014-10-20 18:17:38

标签: excel vba excel-vba

我使用下面的VBA命令通过使用单元格引用作为过滤器,使用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中设置的过滤器。

请帮助解决此错误。

2 个答案:

答案 0 :(得分:2)

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"

(请注意包含您要过滤的值的单引号'

答案 1 :(得分:1)

我看不到你在字符串周围添加单引号的位置。您是否尝试将SQL语句的WHERE子句部分更改为"WHERE Segmentation_ID = '" & Sheets("Perc").Range("A1").Value & "' "