Search code examples
libreoffice-basic

How to create a macro to jump to the end of a document in Libre Office Basic


Each time I open my Libre Office document to add updates, I have to press CTRL+END to jump to the bottom of the document. I thought of adding a button to jump-to-the-bottom, but the Basic it uses is not VBA, so I'm in a pickle. Can anyone give me a sub? As an after-thought; can I add an instruction to the document-startup?? to cursor-jump-to-the-bottom of the file? Please forgive my pants naming conventions, I'm still green! I tried the offline help to no avail. Next I tried Google but could not find an exact sub to match. I then subscribed to the TheDocumentFoundation and was presented with an SO-like Q&A forum. The discobot did not help! I also tried recording a macro which does work ok. The sub code is:

    sub Main
    rem define variables
    dim document   as object
    dim dispatcher as object
    rem get access to the document
    document   = ThisComponent.CurrentController.Frame
    dispatcher =    createUnoService("com.sun.star.frame.DispatchHelper")

    dispatcher.executeDispatch(document, ".uno:GoToEndOfDoc", "",      0, Array())
    end sub

I cannot however add the commands to the document.init or startup.


Solution

  • In fact, the macro for moving the cursor to the end of the document is a little easier to write. Each document has a controller. The text document controller has a "view cursor". You can control this cursor using its methods, in this case you need the .gotoEnd() method.

    So the code can be like this: "if this document is a text document, then get its controller, take the cursor from the controller, make the cursor jump to the end of the text"

    Sub jumpToEnd(Optional oEvent As Variant)
        If  ThisComponent.SupportsService("com.sun.star.text.TextDocument") Then
            ThisComponent.getCurrentController().getViewCursor().gotoEnd(False)
        EndIf 
    End Sub
    

    The best place for this macro is some module in the Standard library under "My Macros" - this library will be loaded immediately after starting the office and macros will be available for execution at any time. (If you want to run this macro only for one document, then you can place it in the Standard library of this document)

    To run the macro automatically, use the Tools - Customize - Events tab

    Set Macro To Open Document

    This is where you specify whether the macro should be executed when you open one specific document or when you open any document.

    Now that you know how to do this, you will probably agree that pressing Ctrl+End is much easier.