Formatting the Field in Dsum - ms-access

In my project I am using dsum to query a table to compare years. But I want to render the field as a year for the comparison.
Public Function GetValue(whatyear) As Long
GetValue = DSum("Modification", "Accounting Totals", "Format([EntryDate],'yyyy') = " & whatyear & " AND [ModType] like *2*")
End Function
I keep getting this error:
Syntax error (missing opeator in query expression
'Format([EntryDate],'yyyy' = 2016 AND [ModType] like *2*"
This is probably an easy one for you VBA Gurus. What do I do?

you need qoutes for the year, and if [ModType] is text, you need qoutes for it as well. in addition, handle null values like this, else if it doesn't find any rows, that will throw another error:
Nz(DSum("Modification", "Accounting Totals", "Format([EntryDate],'yyyy') = '" & whatyear & "' AND [ModType] like '*2*' "), 0)
if [ModType] is a numeric value, then the like operator is not going to work, you need to use another operator such as these: =, >=, <=, BETWEEN

Got it - I had to remove the As Long from the function declaration
If so, you may have zero records and DSum returns Null. Catch that - as O. Gungor showed - with Nz. And get the year as a number:
So:
Public Function GetValue(ByVal whatyear As Integer) As Currency
GetValue = Nz(DSum("Modification", "Accounting Totals", "Year([EntryDate]) = " & whatyear & " AND [ModType] Like '*2*'"), 0)
End Function

Related

Find the position of the first occurrence of any number in string (if present) in MS Access

In MS Access I have a table with a Short Text field named txtPMTaskDesc in which some records contains numbers, and if they do, at different positions in the string. I would like to recover these numbers from the text string if possible for sorting purposes.
There are over 26000 records in the table, so I would rather handle it in a query over using VBA loops etc.
Sample Data
While the end goal is to recover the whole number, I was going to start with just identifying the position of the first numerical value in the string. I have tried a few things to no avail like:
InStr(1,[txtPMTaskDesc],"*[0-9]*")
Once I get that, I was going to use it as a part of a Mid() function to pull out it and the character next to it like below. (its a bit dodgy, but there is never more than a two-digit number in the text string)
IIf(InStr(1,[txtPMTaskDesc],"*[0-9]*")>0,Mid([txtPMTaskDesc],InStr(1,[txtPMTaskDesc],"*[0-9]*"),2)*1,0)
Any assistance appreciated.
If data is truly representative and number always preceded by "- No ", then expression in query can be like:
Val(Mid(txtPMTaskDesc, InStr(txtPMTaskDesc, "- No ") + 5))
If there is no match, a 0 will return, however, if field is null, the expression will error.
If string does not have consistent pattern (numbers always in same position or preceded by some distinct character combination that can be used to locate position), don't think can get what you want without VBA. Either loop through string or explore Regular Expressions aka RegEx. Set reference to Microsoft VBScript Regular Expressions x.x library.
Function GetNum(strS AS String)
Dim re As RegExp, Match As Object
Set re = New RegExp
re.Pattern = "[\d+]+"
Set Match = re.Execute(strS)
GetNum = Null
If Match.Count > 0 Then GetNum = Match(0)
End Function
Input of string "Fuel Injector - No 1 - R&I" returns 1.
Place function in a general module and call it from query.
SELECT table.*, GetNum(Nz(txtPMTaskDesc,"")) AS Num FROM table;
Function returns Null if there is no number match.
Well, does the number you want ALWAYS have a - No xxxx - format?
If yes, then you could have this global function in VBA like this:
Public Function GNUM(v As Variant) As Long
If IsNull(v) Then
GNUM = 0
Exit Function
End If
Dim vBuf As Variant
vBuf = Split(v, " - No ")
Dim strRes As String
If UBound(vBuf) > 0 Then
strRes = Split(vBuf(1), "-")(0)
GNUM = Trim(strRes)
Else
GNUM = 0
End If
End Function
Then your sql will be like this:
SELECT BLA, BLA, txtPMTaskDesc, GNUM([txtPMTaskDesc] AS TaskNum
FROM myTable
So you can create/have a public VBA function, and it can be used in the sql query.
It just a question if " - No -" is ALWAYS that format, then THEN the number follows this
So we have "space" "-" "space" "No" "space" "-" -- then the number and the " -"
How well this will work depends on how consistent this text is.

Trying to display expression if state exists, getting #Error

In my SSRS report, I'm trying to display the City and State if the city exists and I'm doing so with this expression
=IIF(Fields!Ship_To_City.Value, Fields!Ship_To_City.Value & "," & Fields!Ship_To_State.Value, "")
the conditional part of it works, but whenever it's supposed to output the City, State, I get #Error. Any reason why?
An IIF conditional goes like this:
=IIF(boolean_condition, value_if_true, value_if_false)
Now, your IIF looks like this:
=IIF(Fields!Ship_To_City.Value, Fields!Ship_To_City.Value & "," & Fields!Ship_To_State.Value, "")
That is, Fields!Ship_To_City.Value is operating as a boolean value in the boolean_condition part but then as a string in the value_if_true part. One of these isn't going to work.
I assume you want to test that the field isn't null before outputing it, so you want to have an actual boolean condition in your IIF like this:
=IIF(Fields!Ship_To_City.Value <> Nothing, Fields!Ship_To_City.Value & "," & Fields!Ship_To_State.Value, "")

Access VBA Dmin and Dmax on comma seperated decimals

My system is using , as decimal seperator and . as thousands.
When i use the Dmin and Dmax functions in VBA, i get the error:
run-time error 3075 syntax error (comma)
While running this:-
UpperPower = DMin("Column2", "t_table", "Column2" & ">=" & RatedPower)
Where RatedPower is a function variable declared Public RatedPower As Double.
The function is declared double as well.
Everything else works fine with the comma being the decimal seperator.
I have looked into the replace function but I am not sure how to use it in the Dmin function...
What can i do?
Best Regards, Emil.
This will work:
UpperPower = DMin("Column2", "t_table", "Column2 >= " & Replace(RatedPower, ",", "."))
Since the first argument to Replace() must be a string, RatedPower is implicitly converted to a string using the local decimal separator (if non-integer) and no thousands separators.
This code is foolproof, in that it works regardless if the local decimal separator is "." or ","

How can you check for null in a VBA DAO record set?

I have an optional field in a database that I'm pulling out using a DAO Record Set. I need to check whether or not the field is set before I concatenate it with other fields. So far I have the following code snippet which I've tried with both Is and = (that's the obviously wrong syntax [[Is | =]]) to no avail. It appears that if I use = it will not correctly compare with Null and if I use Is then it complains that it's not comparing with an Object.
While Not rs.EOF
If rs.Fields("MiddleInitial") [[Is | =]] Null Then thisMiddleInitial = "" Else thisMiddleInitial = rs.Fields("MiddleInitial")
If prettyName(myLastName, myFirstName, myMiddleInitial) = prettyName(rs.Fields("LastName"), rs.Fields("FirstName"), thisMiddleInitial) Then
MsgBox "Yay!"
End If
rs.MoveNext
Wend
If there's a simpler way to do this I'm totally open to it. prettyName takes 3 Strings as parameters and initially I was just trying to pass rs.Fields("MiddleName") directly but it threw up at a Null value. I'd prefer to do something more direct like that but this is the best I could come up with.
How about:
IsNull(rs.Fields("MiddleInitial").Value)
You could also have a look at this article which has some explanation about Null values in Access VBA apps and how to handle them.
For the example you show, Nz would work:
thisMiddleInitial = Nz(rs!MiddleInitial,"")
Or simply concatenating the string with an empty string:
thisMiddleInitial = rs!MiddleInitial & ""
Your question has been answered by Remou, seems to me, but it occurs to me that you may just be trying to get proper concatenation of the name fields. In that case, you could use Mid() and Null propagation in VBA to get the result.
I don't use separate middle initial fields, so my usual name concatenation formula is:
Mid(("12" + LastName) & (", " + FirstName), 3)
The "12" string at the beginning is going to be tossed away if LastName is Not Null and ignored if it is null, because the + concatenation operator propagates Nulls.
To extend this to include middle intials would look like this:
Mid(("12" + LastName) & (", " + FirstName) & (" " + MiddleInitial), 3)
Assuming your UDF is not doing some kind of complicated cleanup of nicknames/abbreviations/etc., this could replace it entirely, seems to me.
If rst.Fields("MiddleInitial").Value = "Null" Then
This works for me. I use MS SQL Database.
I think the NoMatch option might work in this situation:
If rs.NoMatch = True Then
I prefer using the below to account for both Null and Empty string values. It's a good check to use you have forms collecting values from users.
If Trim(rs.Fields("MiddleInitial") & "") = "" then

Display Parameter(Multi-value) in Report

Can anyone tell me how to display all the selected value of my multi value parameter in SSRS report. When giving parameter.value option it gives error.
You can use the "Join" function to create a single string out of the array of labels, like this:
=Join(Parameters!Product.Label, ",")
=Join(Parameters!Product.Label, vbcrfl) for new line
I didn't know about the join function - Nice! I had written a function that I placed in the code section (report properties->code tab:
Public Function ShowParmValues(ByVal parm as Parameter) as string
Dim s as String
For i as integer = 0 to parm.Count-1
s &= CStr(parm.value(i)) & IIF( i < parm.Count-1, ", ","")
Next
Return s
End Function
Hopefully someone else finds this useful:
Using the Join is the best way to use a multi-value parameter. But what if you want to have an efficient 'Select All'? If there are 100s+ then the query will be very inefficient.
To solve this instead of using a SQL Query as is, change it to using an expression (click the Fx button top right) then build your query something like this (speech marks are necessary):
= "Select * from tProducts Where 1 = 1 "
IIF(Parameters!ProductID.Value(0)=-1,Nothing," And ProductID In (" & Join(Parameters!ProductID.Value,"','") & ")")
In your Parameter do the following:
SELECT -1 As ProductID, 'All' as ProductName Union All
Select
tProducts.ProductID,tProducts.ProductName
FROM
tProducts
By building the query as an expression means you can make the SQL Statement more efficient but also handle the difficulty SQL Server has with handling values in an 'In' statement.