Python Forum
Updating formulas in Excel - best solution
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Updating formulas in Excel - best solution
#3
(Mar-04-2024, 10:23 AM)Aften1961 Wrote: Did you solve the problem?

Partially. I might use translate as below. But to be honest I more willing of creating VBA and launch it using Python.
Translate solution seems be sensitive for what kind of data are copied/included in Excel. Using "translate" solution not always cooperate with my files as for my report I use data from different sources. With VBA I don't have such issue.


#Version 3
from openpyxl import load_workbook
from openpyxl.formula.translate import Translator

# Load the workbook
wb = load_workbook('_MAT_TEMPLATE_Python.xlsx')
ws = wb["Material prices"]

# Get the total number of rows based on column A
total_rows = sum(1 for row in ws.iter_rows(max_col=1, max_row=ws.max_row, values_only=True) if row[0])

# Generate the formula for column B
orig_formula = "=VLOOKUP($A7,'Master data'!$A:$H,2,0)"
orig_cell = 'B7'
ws[orig_cell] = orig_formula

# Apply formulas in column B
for row in range(8, total_rows+1):

    dst_cell = f"B{row}"
    # Apply the formula to the cell translating from cell B7
    ws[dst_cell] = Translator(orig_formula, origin=orig_cell).translate_formula(dst_cell)

# Save the workbook
wb.save("_MAT_TEMPLATE_Python.xlsx")
Reply


Messages In This Thread
RE: Updating formulas in Excel - best solution - by MasterOfDestr - Mar-05-2024, 06:49 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Python openyxl not updating Excel file MrBean12 1 451 Mar-03-2024, 12:16 AM
Last Post: MrBean12
  plotting based on the results of mathematical formulas Timur 1 424 Feb-08-2024, 07:22 PM
Last Post: Gribouillis
  Updating sharepoint excel file odd results cubangt 1 975 Nov-03-2023, 05:13 PM
Last Post: noisefloor
  openpyxl insert list with formulas Irv1n 1 1,625 Sep-16-2021, 08:10 AM
Last Post: Irv1n
  Help with a query - to show possible formulas Yanos 1 1,822 Nov-02-2020, 12:18 AM
Last Post: jefsummers
  How to ignore formulas when reading excel file SriMekala 3 6,647 Aug-16-2019, 04:04 PM
Last Post: buran
  python 3 math formulas where to use () Python101 1 2,363 Jun-09-2019, 09:54 PM
Last Post: micseydel
  Business formulas more help needed!! jy0013 4 3,501 Aug-29-2017, 12:21 AM
Last Post: jy0013

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020