2014-10-20 35 views
1

我正在使用下面的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設置的過濾器。

請幫助解決此錯誤。

回答

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" 

(注意單引號'圍住要過濾的值)

+0

謝謝我在我的過濾器中錯過了單引號......我設置了引號,並得到結果... – 2014-10-20 18:36:53

+0

請注意那些單引號不是' t數值所必需的... – 2014-10-20 21:38:25

+0

@ n8。問題中提供的示例是一個字符串,因此需要引號*。當然,您可以檢查該值是代碼中的字符串還是數字,並在需要時包含/排除引號 – Barranka 2014-10-20 21:44:49

1

我沒有看到你在你的字符串周圍添加單引號。您是否嘗試過將您的SQL語句的WHERE子句部分更改爲"WHERE Segmentation_ID = '" & Sheets("Perc").Range("A1").Value & "' "

+0

謝謝單引號是問題... – 2014-10-20 18:37:15