我正在使用下面的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
設置的過濾器。
請幫助解決此錯誤。
謝謝我在我的過濾器中錯過了單引號......我設置了引號,並得到結果... – 2014-10-20 18:36:53
請注意那些單引號不是' t數值所必需的... – 2014-10-20 21:38:25
@ n8。問題中提供的示例是一個字符串,因此需要引號*。當然,您可以檢查該值是代碼中的字符串還是數字,並在需要時包含/排除引號 – Barranka 2014-10-20 21:44:49