I have a VBA function that I am building for a project and an if statement is continually throwing a Type mismatch errors. Here's the relevant code:
Dim conn As ADODB.Connection
Set conn = New ADODB.Connection
With conn
.ConnectionString = "DRIVER={SQL Server};SERVER=SERVER;DATABASE=DB;Trust_Connection=yes;" ' connection to server
End With
conn.Open
Dim year_goal As ADODB.Recordset
sls_rep_wb.Worksheets(yy & " MO-MO").Activate
Set year_goal = conn.Execute("SOME SQL QUERY THAT RETURNS A SUM NUMERIC")
If IsEmpty(Range("AY3")) & year_goal.RecordCount > 0 Then ' this line throws the error
Range("AY3:" & Range("AY3").Offset(0, 12).Address).Value = (year_goal!Sum) / 12
End If
At first, I was getting an error that indicated one of the iterations returned an empty record set for year_goal, which is why i added in the record count condition. I attempted to use the BOF AND EOF properties to check for an empty record set as well and they gave the same error. This code throws an error even when the record set is not empty. Not sure what the issue is, please help. Thanks!
The operator "&" is only for strings.
The sentence below below:
If IsEmpty(Range("AY3")) & year_goal.RecordCount > 0 Then
It will should be written like this:
If IsEmpty(Range("AY3")) And year_goal.RecordCount > 0 Then
References: https://learn.microsoft.com/en-us/office/vba/language/reference/user-interface-help/and-operator
https://learn.microsoft.com/en-us/office/vba/language/reference/user-interface-help/ampersand-operator