Error assigning pass through query to report recordsource in VBA code

坚强是说给别人听的谎言 提交于 2019-12-25 02:56:16

问题


I have the following code :

    Private Sub Report_Open(Cancel As Integer)
      On Error GoTo ErrorHandler
        Dim isPTQueryExists As Integer
    isPTQueryExists = IsQuery("myTestQuery")
    If isPTQueryExists = -1 Then
    Set qdf = CurrentDb.QueryDefs("myTestQuery")
    qdf.SQL ="my SQL query" 
    Me.RecordSource = "myTestQuery"
    End If
    Else
    Dim DatabaseName As String
    Dim ServerName As String
    ServerName = "XXXX"
    DatabaseName = "XXXX"
    Set qdf = CurrentDb.CreateQueryDef("myTestQuery")
    strConnectionString = "XXXX" 
    qdf.Connect = strConnectionString
   qdf.SQL = "My SQL Query"
   Me.RecordSource = "myTestQuery"
End If
ErrorHandler:
 MsgBox Err.Description
End Sub

********************************************************
      ' FUNCTION: IsTableQuery()
      '
      ' PURPOSE: Determine if a table or query exists.
      '
      ' ARGUMENTS:
      '   DbName: The name of the database. If the database name
      '           is "" the current database is used.
      '    TName: The name of a table or query.
      '
      ' RETURNS: True (it exists) or False (it does not exist).
      '
      '********************************************************
      Function IsQuery(QName As String) As Integer
      Dim Found As Integer
      Dim QueryName As String
      Const NAME_NOT_IN_COLLECTION = 3265
         ' Assume the table or query does not exist.
         Found = False
         ' Trap for any errors.
         On Error Resume Next
         ' See if the name is in the Queries collection.
         QueryName = CurrentDb.QueryDefs(QName$).Name
         If Err <> NAME_NOT_IN_COLLECTION Then Found = True
         IsQuery = Found
      End Function

I have a report . I am trying to set the record source of a query dynamically from VBA code to a pass through query .

I dont have the Query Def created at the design time and i am not specifying any record source for report and design time

In the code , i am checking if the Query Def already exists , if so , i am just changing the SQL property of it and setting the record source .

If the query def is not available , then i am creating a new one an then setting it as record source.

The problem here is : whenever i execute the code , it is showing an error:

"Item not found in collection" . If i click on OK button of message box then it continues to run and then displays the report .

But , i am not sure why the error is occuring ,and why the code is not failing with that error ?

Any thoughts on this? . I have put lot of efforts tounderstand this but in vain

Updated :

If i dont use any error handler , it is not throwing any exception

来源:https://stackoverflow.com/questions/29801466/error-assigning-pass-through-query-to-report-recordsource-in-vba-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!