MS Access,使用基于表选择的字段创建查询

时间:2015-07-28 14:55:13

标签: access-vba ms-access-2010

我有一个MS Access数据库并存储了一个包含所有可用列名(> 100列)的表。我在这个表中添加了一个字段,它只是一个是/否或者是真/假。

我想在VB中构建查询,或者它不必是VB,选择字段基于用户从该表中选择的内容。我认为将一个组合框或列表框添加到用户表单将太忙,因为有超过100列可供选择。我认为他们更容易打开表并选择那种方式,然后单击表单上的一个按钮来调用构建查询,并仅选择用户在Column_Names表中选择的那些字段。

有任何想法/建议吗?

1 个答案:

答案 0 :(得分:0)

I think I figured it out; at least this works for my needs. I added a list box to a User Form which defaults the population off of a query that returns only the fields that have a value of Yes from my Column_Name table.

I then found a function that will I can call that Selects all of the values in this list box.

Then I run this small code to generate the SQL accordingly

 Dim ctlList As Control, varItem As Variant
  Dim strSQL As String
  Dim strSQL2 As String
  Dim qdf As DAO.QueryDef
  Dim qdfDemo As QueryDef
  Call SelectAll(Form_Custom_Criteria!List27)
  Const conQUERY_NAME As String = "qry_custom_fields"
  ' Return Control object variable pointing to list box.
  Set ctlList = Forms!Custom_Criteria!List27
  ' Enumerate through selected items.
      For Each varItem In ctlList.ItemsSelected
      strSQL = strSQL & ctlList.ItemData(varItem) & ", "
       If strSQL = "" Then Exit Sub
         Next varItem
  CurrentDb.QueryDefs.Delete conQUERY_NAME
  On Error GoTo Err_cmdTest_Click
  strSQL_2 = "Select " & Left$(strSQL, Len(strSQL) - 2) & " FROM Table1;"
  Set qdfDemo = CurrentDb.CreateQueryDef(conQUERY_NAME, strSQL_2)

 Exit_cmdTest_Click:
  Exit Sub

  Err_cmdTest_Click:
   MsgBox Err.Description, vbExclamation, "Error in cmdTest_Click()"
  Resume Exit_cmdTest_Click
 End Sub