我有一张工作表,其中包含多列公式。我想使用脚本在该列的下一行中添加下一个范围的公式,而不是手动执行。在这段代码中,我试图实现这一目标,但每次它都会进入“else”,即使前一个单元格有一个公式。请让我知道我哪里出错了。谢谢。
tokenPath='path_to_token_file'
scopes = ['https://www.googleapis.com/auth/spreadsheets',
'https://www.googleapis.com/auth/drive']
credentials = Credentials.from_service_account_file(tokenPath, scopes=scopes)
client = gspread.authorize(credentials)
sheet_title = 'my_sheet_title'
sheet = client.open(sheet_title)
spreadsheet_id = 'my_spreadsheet_id'
worksheet = sheet.get_worksheet(1) # 2nd sheet so index=1
# Find the last cell with a formula in column C
col_p_values = worksheet.col_values(3) # Column C is index 3
last_formula_cell = None
for row_number, value in enumerate(col_p_values, start=1):
if value.startswith('=SUM('):
last_formula_cell = worksheet.cell(row_number, 3) # Column C is index 3
break
if last_formula_cell:
previous_formula = last_formula_cell.formula
start_row = int(previous_formula.split(':')[1][1:])
new_start_row = start_row + 1
new_end_row = new_start_row + 6
new_formula = f"=SUM(my_sheet_name!P{new_start_row}:P{new_end_row})"
# Update the cell below the last formula cell with the new formula
new_formula_range = f"C{last_formula_cell.row + 1}" # updating column C
worksheet.update(new_formula_range, new_formula)
print("Formula updated successfully.")
else:
print("No formula found in the specified column.")
建议:
根据我的评论,
col_p_values = worksheet.col_values(3)
只会填充单元格值数组,而不是单元格公式。
您可以尝试使用公式获取最后一个单元格:
tokenPath='path_to_token_file'
scopes = ['https://www.googleapis.com/auth/spreadsheets',
'https://www.googleapis.com/auth/drive']
credentials = Credentials.from_service_account_file(tokenPath, scopes=scopes)
client = gspread.authorize(credentials)
sheet_title = 'my_sheet_title'
sheet = client.open(sheet_title)
spreadsheet_id = 'my_spreadsheet_id'
worksheet = sheet.get_worksheet(1) # 2nd sheet so index=1
# Find the last cell with a formula in column C
col_p_length = len(worksheet.col_values(3))
col_p_values = worksheet.cell(col_p_length, 3, value_render_option='FORMULA').value
last_formula_cell = None
print(col_p_values)
从这里开始,这只能作为使用公式获取 C 列上最后一个单元格的参考,从那里您需要调整替换公式的逻辑。
参考: