Friday, May 20, 2016

Concatenate full name in reverse order with comma and optional title


Sometimes it is preferrable to output full name as a single field/column like
<last_name>, <title> <first_name>
where title and first name are both optional (as occurs in the real world). Because of the different combinations where title and/or first name are null there should be some conditional logic with concatenation. But you can do correct concatenation in a single expression using the fact that coalesce(right(title,0),', ') will return empty string when title is not null and  separator', ' otherwise:

select 
trim(
upper(family_name) || coalesce(', ' || title || ' ', '') || coalesce(coalesce(right(title,0),', ') || given_names, '')
) as person_name 
from person

Thursday, May 19, 2016

Move cursor to specific text in Word VBA




Sometimes it's necessary to replace placeholders (e.g. <content_placeholder1>) in a Word document with some generated or imported content using VBA macro. Just replacing the placeholder text via Selection.Find.Execute Replace:=wdReplaceAll  will not move a cursor, you need to do it as a separate step like below:

Sub moveToPlaceholder(tableName As String)

    Dim placeholderText As String

    placeholderText = "<" & tableName & ">"
    
    ' first find
    With Selection.Find
      .Text = placeholderText
      .Forward = True
      .Wrap = wdFindContinue
      .Format = False
      .MatchCase = False
      .MatchWholeWord = False
      .MatchWildcards = False
      .Execute
    End With
    
    ' now move cursor at the
    Selection.EndKey Unit:=wdLine
    
    ' now replace
    With Selection.Find
      .Text = placeholderText
      .Replacement.Text = ""
      .Forward = True
      .Wrap = wdFindContinue
      .Format = False
      .MatchCase = False
      .MatchWholeWord = False
      .MatchWildcards = False
      .Execute Replace:=wdReplaceAll
    End With
  
End Sub