1

我正在处理 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';
4

1 回答 1

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

有点解决方法,但它得到了解决方案。

于 2013-10-17T12:10:52.207 回答