I'm moving forms over from one Access database to another. When I try to compile the new database, it gives a "Variable not defined" error. This only happens when using Option Explicit. The variable is a AccessField data type that is selected by the form's SQL query. This compiles fine on the Access database that I'm moving it from, so I'm completely lost trying to figure out what's wrong?
I seem to have the exact same problem that never was solved in this old thread: https://bytes.com/topic/access/answers/896346-variable-not-defined-error-field-exists
It's more than one instance. Anything that references an AccessField that is not declared as a variable will return that error when Option Explicit is used.
For instance, the form is using the query:
Select * from BM where ClientID =143 and Month(BMDate) = 4 and year(bmdate) =2018 order by bmdate
And the VBA code inside that form would fail here with that error:
Option Explicit
Option Compare Database
Private Sub Form_Load()
If IsNull(RecNbr) Then
'Code fails with RecNbr on line above when I try to compile
'RecNbr is a field selected from the query and is not declared as a variable
End If
End Sub
This may or may not work, but it's too long for a comment.
This post in your linked thread seems to have an explanation:
In the form design view, the Field List and the drop-down for the Control Source for a control reflect the current table design; but VBA seems to have a stale copy of the form's recordsource schema.
Try this to re-sync VBA's cache (?) of the record source:
As a note, I find find code better readable when using Me.RecNbr
instead of RecNbr
when refering to form controls or fields (as opposed to VBA variables).
If the above still doesn't compile, you can use Me!RecNbr
.
Useful reading: Bang Notation and Dot Notation in VBA and MS-Access
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With