[Solved] Write a loop to keep the formula

Creating a macro - Writing a Script - Using the API (OpenOffice Basic, Python, BeanShell, JavaScript)
Locked
luofeiyu
Posts: 55
Joined: Thu Sep 14, 2017 2:11 am

[Solved] Write a loop to keep the formula

Post by luofeiyu »

From column B to F, i want to keep the expression.

Code: Select all

b5=b2*b3
c5=c2*c3
d5=d2*d3
e5=e2*e3
f5=f2*f3
When i is from 1 to 5,the "getCellByPosition(i, 4)" can express b5,c5,d5,e5,f5,how to express the right part such as "b2*b3"?

Code: Select all

sub strtest()
    oDoc = ThisComponent
    Sheets = oDoc.getSheets()
    Sheet = Sheets.getByName("Sheet1")
    for  i=1 to 5
       Sheet.getCellByPosition(i, 4).formula = "=some_string_expression"
    next 
end sub
Last edited by RoryOF on Sat Feb 01, 2025 12:09 pm, edited 2 times in total.
Reason: Added green tick [RoryOF, Moderator]
LibreOffice 24.8 on Debian 12
User avatar
robleyd
Moderator
Posts: 5429
Joined: Mon Aug 19, 2013 3:47 am
Location: Murbko, Australia

Re: How can write a for loop to keep the formula?

Post by robleyd »

Slackware 15 64 bit
Apache OpenOffice 4.1.15
LibreOffice 25.8.1.1; SlackBuild for 25.8.1 by Eric Hameleers
---------------------
Roses are Red, Violets are Blue]
Unexpected '{' on line 32
.
User avatar
karolus
Volunteer
Posts: 1231
Joined: Sat Jul 02, 2011 9:47 am

Re: Solved--Write a loop to keep the formula

Post by karolus »

python:

Code: Select all

doc = XSCRIPTCONTEXT.getDocument()
columns = "BCDEF"
out =[[f"={c}2*{c}3" for c in columns ]]
cellrange = doc.Sheets["Sheet1"]["B5:F5"]
cellrange.FormulaArray = out
Libreoffice 25.2… on Debian 13 (trixie) (on RaspberryPI5)
Libreoffice 25.8… flatpak on Debian 13 (Bookworm) (on RaspberryPI5)
Locked