How to change "ThisComponent"?

I want to create a Write document from a Calc macro.

The actual creation works fine but “ThisComponent” still points to the Calc document, so I can’t insert any text into my new Write document. I have tried to bring the Write document to the front, and tried to make it active in two different ways but ThisComponent doesn’t change.

Can anyone point to my error?

Sub Main
 Dim oFF           REM FilterFactory service
  
  oFF = createUnoService( "com.sun.star.document.FilterFactory" )
  
  REM Create a Write doc
  oDoc = StarDesktop.loadComponentFromURL( "private:factory/swriter", "_blank", 0, Array() )

  REM bring the writer doc to the front.  This seems to happen anyway.
  oDoc.CurrentController.Frame.ContainerWindow.toFront()
  
  REM Try to make the writer doc active one way
  StarDesktop.setActiveFrame(oDoc.CurrentController.Frame)

  REM Try to make the writer doc active another way
  oDoc.CurrentController.Frame.Activate()
  
  REM I would hope that by now, ThisComponent is a TextDocument
  If ThisComponent.supportsService("com.sun.star.text.TextDocument") Then
    MsgBox "Success - this is a TextDocument!"
  else
    REM But it isnt :-(
  	MsgBox "Failed :-("
  End If
  
  REM try writing some text into the document.  This silently fails because we are not in the text document.
  fnDispatch("InsertText", array("Text", "The quick brown fox jumped over the lazy dogs." ))

End Sub

Hi,Gaffer

I think when you write the macro in Calc Document, " ThisComponent" means Calc document.
So, “ThisComponent.supportsService(“com.sun.star.text.TextDocument”)” will return false.
I guess your correct code mean following ;

Sub Main
Dim oDoc as Object, oText as Object, oInsertText as String
	oDoc = StarDesktop.loadComponentFromURL( "private:factory/swriter", "_blank", 0, Array())
	oText = oDoc.getText()
	oInsrtText = "The quick brown fox jumped over the lazy dogs."
	oText.insertString(oText.getStart(), oInsrtText , false)
End Sub

Many thanks. Your example has set me in the right direction. That is very helpful.