迭代数据库并删除查询

时间:2015-06-23 14:19:56

标签: ms-access access-vba

我正在尝试迭代一个包含数据库名称的表,打开数据库,检查是否存在查询,是否删除它,然后从数据库导入一个查询,正在执行此代码。我一直在Set badqueryname = "qry_InformationMailer"的行上收到编译时错误,我正在尝试用它来设置要删除的查询的名称。这是该行抛出的错误

object required

完整语法:

Option Compare Database
Option Base 1
Private Sub fur()
  Dim ws As DAO.Workspace
  Dim db As DAO.Database
  Dim qd As DAO.QueryDef
  Dim rstTableName As DAO.Recordset
  Dim myArray() As String
  Dim intArraySize As Integer
  Dim iCounter As Integer
  Dim qryLoop As QueryDef
  Dim exists As String
  Dim dbs As Database
  Dim badqueryname As String
  'Compile error of object required on below line
  Set badqueryname = "qry_InformationMailer"
  Set rstTableName = CurrentDb.OpenRecordset("tbl_Data")
  If Not rstTableName.EOF Then
    rstTableName.MoveFirst
    intArraySize = rstTableName.RecordCount
    iCounter = 1
    ReDim myArray(intArraySize)
    Do Until rstTableName.EOF
      myArray(iCounter) = rstTableName.Fields("ProgramName")
      iCounter = iCounter + 1
      rstTableName.MoveNext
    Loop
End If
If IsObject(rstTableName) Then Set rstTableName = Nothing
  Set qd = CurrentDb.QueryDefs("qry_InformationMailer")
  Set ws = DBEngine(0)
  For l = LBound(myArray) To UBound(myArray)
    Set db = ws.OpenDatabase("C:\" & Trim(myArray(l)) & ".mdb")
    For Each qryLoop In CurrentDb.QueryDefs
        If qry.LoopName = badqueryname Then
            exists = "Yes"
            DoCmd.DeleteObject acQuery, badqueryname
            Exit For
        End If
    Next
    On Error Resume Next
    db.CreateQueryDef qd.Name, qd.SQl
    db.Close
    Set db = Nothing
  Next l
End Sub

1 个答案:

答案 0 :(得分:1)

为简单变量类型指定值时,请勿使用Set

'Set badqueryname = "qry_InformationMailer"
badqueryname = "qry_InformationMailer"

或者,如果您愿意,可以使用Let代替Set

Let badqueryname = "qry_InformationMailer"

但我不再经常使用Let

实际上,在您的代码中, badqueryname 的值在分配其值后永远不会再次更改。换句话说,它被用作常量,所以你可以让它成为常数。

  Const badqueryname As String = "qry_InformationMailer"

其中一项更改应消除对象所需的错误。但是,在此行中您将遇到未声明的 qry 错误...

If qry.LoopName = badqueryname Then

Option Explicit添加到模块的声明部分,然后从VB编辑器的主菜单运行Debug-> Compile。

编译器也应该在这里抱怨因为 l 是未声明的......

For l = LBound(myArray) To UBound(myArray)

修复编译器抱怨的任何内容,然后再次运行Debug-> Compile。重复,直到没有编译错误。