I've created below Excel function which connects to an access database with ADODB (approx 10k lines). It generally works but there are two main issues:
- It is unreliable: often it returns 0 while the result should be different
- It is definitely slow
Any suggestion on how to improve?
Public Function TotaleSQL(Cat As String, SubCat As String, Anno As Integer) As Long
On Error Resume Next
Dim cn As Object, rs As Object, output As String, sql As String
Dim src As String
Dim Total As Long
Dim CatLong As String
src = "Z:\Report.accdb"
'---Connecting to the Data Source---
Set cn = CreateObject("ADODB.Connection")
With cn
.Provider = "Microsoft.ACE.OLEDB.12.0"
.connectionstring = "Data Source=" & src & ";Persist Security Info=False"
.Open
End With
'---Run the SQL SELECT Query---
CatLong = "'" & Cat & ":" & SubCat & "'"
sql = "SELECT Report.Withdrawal, Report.Deposit, Report.Category, Report.Date FROM Report WHERE (((Report.Category)=" & CatLong & ") AND ((Year([date]))=" & Anno & "));"
'sql = "SELECT * FROM [Sheet1$]"
Set rs = cn.Execute(sql)
Total = 0
Do
Total = Total + Val(rs(1) & "") - Val(rs(0) & "")
rs.Movenext
Loop Until rs.EOF
'---Clean up---
rs.Close
cn.Close
Set cn = Nothing
Set rs = Nothing
TotaleSQL = Total
End Function
On Error Resume Nextbecause this line hides all error messages, but the errors still occur, you just cannot see their messages. So if you don't see the errors you cannot fix them and if you don't fix them the code does not work as intended. Remove that line and fix your errors instead. • You might benefit from VBA Error Handling – A Complete Guide.Doloop that loops through all records (if there are many it slows down the process a lot). You obviously just subtract two values and sum them up in total. Try to figure out how to do this in SQL so you don't need to loop. It should be possible with one SQL statement to get that total, without having to loop.