Search code examples
vbams-accessruntime-error

MS Access VBA - Procedure won't recognize form


I'm trying to run a pretty simple procedure here, just loading records into a pop-up form. For some reason the database won't recognize the form. I'm getting error 2450. I've been researching the error and am concerned. When I modify the names and rerun the code in a copyDB, I get the same error. Is there something I'm missing in my code that's running into this? Thanks - any advice is appreciated

Private Sub btn_ViewAgcyInfo_Click()
Dim DB3p As Database
Dim rdst3p As Recordset
Dim txt_AgencyName As String
Dim txt_AgencyNo As String
Dim txt_Address1 As String
Dim txt_Address2 As String
Dim txt_City As String
Dim txt_State As String
Dim txt_Zip As String
Dim txt_Phone As String
Dim cmb_3_AgencyID As String

Dim ViewAgency As Form


Set DB3p = CurrentDb
Set rdst3p = DB3p.OpenRecordset("SELECT [2_AGENCY].[2_AgcyName], [2_AGENCY].[2_Address1], [2_AGENCY].[2_Address2], [2_AGENCY].[2_City], [2_AGENCY].[2_State], [2_AGENCY].[2_Zip], [2_AGENCY].[2_Phone], [2_AGENCY].[2_AgcyNo] " & _
"FROM 2_AGENCY " & _
"WHERE ((([2_AGENCY].[2_AgcyNo])='" & Me.cmb_3_AgencyID & "'));")

rdst3p.MoveLast

Set ViewAgency = Forms("AgencyInfo")

ViewAgency![txt_AgencyName].Value = rdst3p.Fields(0).Value
ViewAgency![txt_AgencyNo].Value = rdst3p.Fields(7).Value
ViewAgency![txt_Address1].Value = rdst3p.Fields(1).Value
ViewAgency![txt_Address2].Value = rdst3p.Fields(2).Value
ViewAgency![txt_City].Value = rdst3p.Fields(3).Value
ViewAgency![txt_State].Value = rdst3p.Fields(4).Value
ViewAgency![txt_Zip].Value = rdst3p.Fields(5).Value
ViewAgency![txt_Phone].Value = rdst3p.Fields(6).Value


Set DB3p = Nothing
Set rdst3p = Nothing
Set ViewAgency = Nothing

End Sub

Solution

  • Not entirely sure, but I believe the form must be declared as Dim ViewAgency As Access.Form and must be loaded to get a reference of it.

    But you don't really need to declare a form variable, just reference it once using the With statement.

    With Forms.AgencyInfo
       .txt_AgencyName.Value = rdst3p.Fields(0).Value
       .txt_AgencyNo.Value = rdst3p.Fields(7).Value
       '...
    End With
    

    No need for the bang ! operator either. Use of common dot in this instance is absolutely valid and much clearer.