views:

635

answers:

2

I'm generating titles out of a few other fields, and want the "right" way to do:

Me.Title.Value = Join(Array([Conference], [Speaker], partstr), " - ")

Except any of [conference], [speaker] or partstr might be null, and I don't want the extra "-"'s. Are there any functions that'll make this job straightforward?

+1  A: 

Nope - you'll have to check each one and then cleanup at the end

Dim Temp As String

If Not IsNull([Conference]) Then
  Temp = Temp & [Conference] & " - "
End If

If Not IsNull([Speaker]) Then
  Temp = Temp & [Speaker] & " - "
End If

If Not IsNull(partstr) Then
  Temp = Temp & partstr & " - "
End If

If Temp > "" then
  Me.Title.Value = Left(Temp, Len(Temp) - 3)
Else
  Me.Title.Value = Null
End If

Revised with generic function:

Public Function JoinEx(ByVal pArray As Variant, ByVal pDelimiter As String) As String

  Dim sTemp As String
  Dim iCtr As Integer

  For iCtr = 0 To UBound(pArray)
    If Not IsNull(pArray(iCtr)) Then
      sTemp = sTemp & pArray(iCtr) & pDelimiter
    End If
  Next

  If sTemp > "" Then
   JoinEx = Left(sTemp, Len(sTemp) - Len(pDelimiter))
  End If

End Function

Calling Example:

 JoinEx(Array("one","two","three"), " - ")  'Returns "One - Two - Three"
 JoinEx(Array(null,"two","three"), " - ")  'Returns "Two - Three"
DJ
I am still hoping for a better answer, I'll do this a bunch of times, and don't want to duplicate so much code.
Thelema
I feel your pain - however with a little more work you could create a generic function that accepts an array and a delimiter and returns the string.
DJ
Revised with function :-)
DJ
ah, this is much more like it. I'd give you another upvote if I could.
Thelema
Experts say that concatenating a possibly Null field with a zero-length string and testing its length is faster than merely checking for Null or comparing the concatenated result to a ZLS. And, BTW, any time you need a ZLS in Access VBA, be sure to use the vbNullString constant instead of "".
David-W-Fenton
A: 

A complete re-write, and this time properly tested:

 IIf(IsNull(Partstr), IIf(IsNull(Conference), Speaker, Conference & " - " + Speaker), Conference + " - " & Speaker + " - " & Partstr)
Remou
If one of the items are null then that turns the whole result to null which I don't think the OP wants.
DJ
Sorry remou it still won't work - if [conference] is null and the others are not - your solution will return "None" instead of "Speaker - Partstr"
DJ
You are right, so I have redone the whole thing paying more attention :(
Remou