我正在使用Access中的一个基本上具有此功能的对话框。我希望用户从组合框中选择一个表,然后更改查询以创建必要信息的选择视图。这是对话框的代码
Private Sub cmdOK_Click()
Dim db As DAO.Database
Dim qdf As DAO.QueryDef
Dim strSQL As String
Set db = CurrentDb
Set qdf = db.QueryDefs("qryPendingQS")
strSQL = "SELECT [Event Start Date] AS [Event Date], [PO Sent _Date] AS [PO Sent Date], [Brand Name] AS Vendor, PO, [Units _Sold] AS [Units Sold], [Routing Date/Time EST] AS Shipped, [Date and _Time of Arrival] AS ETA, [Department Name] AS Category " & _
"FROM Me.cbotable.Value " & _
"WHERE table3 ='" & Me.cbotable.Value & "';"
qdf.SQL = strSQL
DoCmd.OpenQuery "qryPendingQS"
DoCmd.Close acForm, Me.Name
Set qdf = Nothing
Set db = Nothing
End Sub
大部分事情都很好,但问题的这一部分出现了问题。
strSQL = "SELECT [Event Start Date] AS [Event Date], [PO Sent _Date] AS [PO Sent Date], [Brand Name] AS Vendor, PO, [Units _Sold] AS [Units Sold], [Routing Date/Time EST] AS Shipped, [Date and _Time of Arrival] AS ETA, [Department Name] AS Category " & _
"FROM table3" & _
"WHERE table3 ='" & Me.cbotable.Value & "';"
这是之前的尝试,但我知道您无法根据WHERE子句更改表。所以我的问题是,如何根据组合框中选择的内容动态更改FROM语句
这是查询尝试执行时SQL代码的外观:
SELECT [Event Start Date] AS [Event Date], [PO Sent _Date] AS [PO Sent Date], [Brand Name] AS Vendor, PO, [Units _Sold] AS [Units Sold], [Routing Date/Time EST] AS Shipped, [Date and _Time of Arrival] AS ETA, [Department Name] AS Category
FROM table3
WHERE table3 ='QS Log';
答案 0 :(得分:1)
我自己找到了冲突的解决方案,因为我知道你无法通过SQL代码传递参数。由于我在VBA中获得了代码,因此我决定将SQL语句拆分为两个字符串,一个包含“Select * From”,另一个字符串成为组合框值。然后我将这些值一起添加到一个字符串并将其推送到查询。
Private Sub cmdOK_Click()
Dim Db As DAO.Database
Dim qdf As DAO.QueryDef
Dim strSQL As String
Set Db = CurrentDb
Set qdf = Db.QueryDefs("qryPendingQS")
Dim strQryFirstPart As String
Dim strQryWhole As String
Dim strTableName As String
strQryFirstPart = "Select * FROM "
strTableName = Me.cbotable.Value
strQryWhole = strQryFirstPart & "[" & strTableName & "]"
qdf.SQL = strQryWhole
Debug.Print strQryWhole
End Sub
有点解决方法,但它得到了解决方案。