Read Selected Text and Select Part of Text in TextField Control Using LibreOffice Basic Macro

2 min

This tutorial will show how to select a part of text and how to read the selected text from a TextBox control in LibreOffice using Basic macro.


This tutorial assumes that you know how to create a simple macro and a simple dialog. If you are unaware of the same, read below two tutorials before you proceed.

Using form controls
Using dialog controls

If you are looking for something else, head over to below link which contains all the LibreOffice macro tutorials list:

Macro Tutorial Index

TextField โ€“ How to Add in a Dialog

To add a TextField, click below icon and drag it to a new dialog.

How to read Selected Text

To read the selected portion of the text box string, use getSelectedText() method of textbox control.


oTextField = oDialog1.getControl("TextField1")
MsgBox oTextField.getSelectedText()

Screenshot of a getSelectedText() method in action:
TextBox - getSelectedText

TextBox - getSelectedText-Read

How to select a part of textbox text

To select a substring of textbox text, use setSelection() method. setSelection() method takes the Struct Selection as argument. Structure Selection have two elements i.e. Min and Max. Min speifies the lower limit of the range and Max refers to upper limit of the range.

Before using the Selection structure, it needs to be defined and loaded with values. To define a structure use createUnoStruct function which takes as argument to create instance of selection structure.

After creating the selection instance, the Min and Max values can be set.

Dim oSelection 
    oSelection = createUnoStruct( "" ) 
    With oSelection 
       .Min = 5
       .Max = 7
    End With

Then the selection object can be passed into setSelection method as argument.

oTextField = oDialog1.getControl("TextField1")

Screenshot of setSelection is in action:
Select Part of Text

Complete Macro

To run, Copy and paste this entire code block below in Macro Editor in LibreOffice.

Dim oDialog1 As Object
Sub StartDialog1()
    oDialog1 = LoadDialog("Standard", "Dialog1")
End Sub

Sub test()
Dim oSelection 'Libreoffice
    oSelection = createUnoStruct( "" ) 
    With oSelection 
       .Min = 4
       .Max = 7
    End With 
	oTextField = oDialog1.getControl("TextField1")
End Sub

Function References โ€“ Used in this article

Looking for Something Else?

If you are looking for something else in LibreOffice macro tutorials, Or, wants to learn more about it, please follow below link for complete Macro Tutorials Index:

LibreOffice Macro Tutorial Index


Creator and author of Connect with me via Telegram, ๐• (Twitter), or send us an email.
Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks
View all comments