I want to create a Python macro that deletes rows by their IDs. I want to display a pop up window with a text box where the user can insert the IDs to be deleted (e.g. “1, 5, 78”). Is that possible with a macro?
Here’s my current code:
import uno
def RemoveRowsByIds(*args):
ctx = uno.getComponentContext()
smgr = ctx.ServiceManager
# Get the desktop and load the current LibreOffice document
desktop = smgr.createInstanceWithContext("com.sun.star.frame.Desktop", ctx)
model = desktop.getCurrentComponent()
if not model or not hasattr(model, "Sheets"):
raise RuntimeError("Please open a Calc document and select a sheet.")
# Access the active sheet
active_sheet = model.CurrentController.ActiveSheet
# Parse the list of row IDs
row_ids_input = args[0] if args else ""
row_ids = list(map(int, row_ids_input.split(',')))
# Sort the row IDs in reverse order to maintain correct indices when deleting rows
row_ids.sort(reverse=True)
for row_id in row_ids:
active_sheet.Rows.removeByIndex(row_id - 1, 1) # `row_id - 1` because row indices are 0-based