Unable to set properties properly for CellStyle

I’m trying to create a macro, that creates and adds a style to the current document, that has CellBackColor set.

I’m able to set the values, but further access throws error, as explained in the below macro.

    Dim T4Style
    Dim oCellStyles

	oCellStyles = ThisComponent.StyleFamilies("CellStyles")
	T4Style = ThisComponent.createInstance("com.sun.star.style.CellStyle")
	Print "T4Style " & T4Style.getImplementationName() ' ScStyleObj

	T4Style.Name = "T4"
	T4Style.CellBackColor = RGB(0, 255, 0) ' Able to set CellBackColor
	
   ' Adding T4Style to document
	If oCellStyles.hasByName("T4") Then
		oCellStyles.removeByName("T4")
		oCellStyles.insertByName("T4", T4Style)
	End If
	
   ' Able to access and use inbuilt style 'Error'
	Print "ErrorStyle " & oCellStyles.getByName("Error").getImplementationName ' ScStyleObj
	Print oCellStyles.getByName("Error").CellBackColor ' Prints 13369344
	Print VarType(oCellStyles.getByName("Error").CellBackColor) ' Prints 3
	
	' Both Throws:
	' Inadmissible value or data type.
	' Data type mismatch.
	Print VarType(T4Style.CellBackColor)
	Print T4Style.CellBackColor

The “T4” style gets added to the document, but the CellBackColor is not set.

Direct formatting works: bookRange.CellBackColor = RGB(0, 255, 0), but I’m trying to set ConditionalFormat for cells, so I can’t use direct formatting in this case.

Thanks.

Think first, code later!

Sub Main
	doc = thisComponent
	Styles = doc.StyleFamilies("CellStyles")		
	If not Styles.hasByName("T4") Then
		T4Style = doc.createInstance("com.sun.star.style.CellStyle")
		Styles.insertByName("T4", T4Style)
	end if	
	'Styles.getByName("T4").CellBackColor = RGB(0,255,0)'
    'better:'
    T4Style.CellBackColor = RGB(0,255,0)
End Sub

Thank you, this worked! I guess we should insert the style and then set the values.

yes, but more important is to switch from »if …« to »if not …« you spot it?

Oh, but that was my intention at that particular time. T4 was already available in the document I was testing. So every time it was getting removed and re-inserted.