Don’t you just love when an acre of (very nice and easy to read, BTW) code becomes a ‘one liner’
Not most of the time.
Duane's example is fine, it is clear and efficient. However, in general I would say that is not the case that shorter is better, especially in VBA. Do not confuse short code with efficiency, readability, maintainability, portability, scalabiltiy, and debugability.
The amount of lines of code often has little to do with what is compiled and how efficient it runs. On this site I see people post a ton of code that they cannot debug, noone can understand, and it can never be reused. Often they try to eat the elephant at once without breaking it into pieces.
I also recommend that any function called by an Access query should be in this form.
Code:
Public Function somefunction(variantArgument As Variant) As variant
'First always check that a null did not get passed.
'use isnull, isnumeric, etc
If IsNumeric(variantArgument) Then
'Other error checking argument validation
'your code here
'return a variant or string
End If
End Function
Because it is highly likely that a query can contain a null, I always make the arguments variants. The returntype can be a string or variant but not a numeric or date. This can be a real pain if not accounted for. If the return type is numeric or a date you will return a default value and not a null. At least with a string you return an empty string so that is fine.
So assume I have a table of 8k records and have 20 records with a null for the date, doing this
Public Function GetDateFromString(varDate As String)
will cause a lot of problems. Even if the current query requires a value, there may be a later date when you want to use that function for queries with nulls.
I could have wrote the original code as a one liner, but I would never write it that way especially if sharing with someone.
Code:
Public Function GetDateFromString(varDate As Variant) As variant
GetDateFromString = DateSerial(left(varDate,4),midVardate(5,2),midVardate(7,2)
End Function
It is harder to debug and harder to read and easier to make a mistake. The local variables are not needed, but the readability outweighs any performance hit.
Most of the VBA code I write is far longer than it needs to be. I often spell out default properties and methods and most of the time try to fully qualify objects. May be longer but most of my code can be shared with little or no comments to explain it. VBA is a really sloppy language so the more specificity often is better.
My favorite are when people ask why this does not work
current db.execute (some huge sql string with embedded iif functions, other functions, tons of string and date formatting)