HillTJ
To train a dog, first know more than the dog..
- Local time
- Today, 04:50
- Joined
- Apr 1, 2019
- Messages
- 731
Friends,
I'm pretty stoked that I was able to write code to return a value based upon a "select top 1' query. To me it's one of those 'pivotal' moments in learning. There are cases where the select query does not return a value. I trap these cases with an 'on error' routine, but question whether there is a better method. To me, I'd rather not generate the error in the first place rather than trap it after it's occurred. I would really like an opinion on this method & if someone has a better technique, then I'd really like to adopt it. Seems to me that trapping the error after it's occurred is a bit like putting the cart before the horse & something I usually figure out in my code & leave error trapping to those 'unforeseen' errors. Appreciate any input. The code is reproduced below;
I'm pretty stoked that I was able to write code to return a value based upon a "select top 1' query. To me it's one of those 'pivotal' moments in learning. There are cases where the select query does not return a value. I trap these cases with an 'on error' routine, but question whether there is a better method. To me, I'd rather not generate the error in the first place rather than trap it after it's occurred. I would really like an opinion on this method & if someone has a better technique, then I'd really like to adopt it. Seems to me that trapping the error after it's occurred is a bit like putting the cart before the horse & something I usually figure out in my code & leave error trapping to those 'unforeseen' errors. Appreciate any input. The code is reproduced below;
Code:
Option Compare Database
Option Explicit
Public Function CostAtDate(PartID As Long, SupplierID As Long, TransactionDate As Date)
Dim strSql As String
Dim rst As DAO.Recordset
Dim CostPrice As Currency
Const conJetDate = "\#mm\/dd\/yyyy\#"
On Error GoTo ErrorHandler
strSql = "Select TOP 1 UnitPrice from qryPriceHistorySortedDescByEffectiveDate WHERE EffectiveDate<= " & Format(TransactionDate, conJetDate) & " And SupplierID = " & SupplierID & " and PartID =" & PartID & ""
Set rst = CurrentDb.OpenRecordset(strSql)
CostPrice = rst.Fields("UnitPrice").value
CostAtDate = CostPrice
ExitError:
rst.Close
Set rst = Nothing
Exit Function
ErrorHandler:
Select Case Err.Number
Case 3021 ' Could not find a match in the Recordset
MsgBox "No Pricing Set Up", vbOKOnly, "Costing Error"
CostAtDate = 0
GoTo ExitError
Case 999
Resume Next
Case Else
Call LogError(Err.Number, Err.Description, "Cost by Date by Product Error")
Resume ExitError
End Select
End Function