Unable to change cell style in calc

I need to change cell styles using macros (mainly background colors), and I have a following example. It works sometimes (it works sometimes in LibreOffice 5.1.6, but not in 5.2.4 and 5.2.5), but I’m unable to understand why it works sometimes and why it does not work sometimes.
Where can I find a good tutorial about LibreOffice macro language? Examples from google are often misleading.
Thank you!

 Sub FormatRange as string

     Dim Doc As Object, Sheet As Object, Cell As Object, Range As Object
     Dim StyleFamilies As Object, CellStyles As Object
     Dim CellStyle As Object, NewStyle As Object

     Doc = ThisComponent
     Sheet = ThisComponent.CurrentController.ActiveSheet
     StyleFamilies = Doc.StyleFamilies
     CellStyles = StyleFamilies.getByName("CellStyles")

    If CellStyles.hasByName("MyTestStyle") Then
     GoTo Alreadyexists
    Else
     NewStyle = Doc.createInstance("com.sun.star.style.CellStyle")
     CellStyles.insertByName("MyTestStyle", NewStyle)
     NewStyle.ParentStyle = "Default"
     CellStyle = CellStyles.getByName("MyTestStyle")

     With CellStyle
	.CharWeight = com.sun.star.awt.FontWeight.BOLD
	.CharFontName = "Courier"
	.HoriJustify = 2		
	.CharHeight = 12
	.CellBackColor = RGB(255,141,56)
   End With
    End If

    Alreadyexists:
    Range = Sheet.getCellRangeByName("O1:O6")
    Range.CellStyle = "MyTestStyle"

    FormatRange = "?"    'WTF??'
   End Sub

your crumpy code works for me with LO5.3.0.3 Linux, but anyway … I dit some clean up:

sub FormatRange()

   doc = ThisComponent
   Sheet = doc.CurrentController.ActiveSheet
   StyleFamilies = doc.StyleFamilies
   CellStyles = StyleFamilies.getByName("CellStyles")

   If not CellStyles.hasByName("MyTestStyle") Then
       NewStyle = Doc.createInstance("com.sun.star.style.CellStyle")
       CellStyles.insertByName("MyTestStyle", NewStyle)
       With NewStyle
           .ParentStyle = "Default"
           .CharWeight = com.sun.star.awt.FontWeight.BOLD
           .CharFontName = "Courier"
           .HoriJustify = 2        
           .CharHeight = 12
           .CellBackColor = RGB(255,141,56)
        End With
  End If

  Range = Sheet.getCellRangeByName("O1:O6")
  Range.CellStyle = "MyTestStyle"
End sub