Skip to main content
 首页 » 编程设计

python之使用另一个单元格的值动态替换单元格公式的一部分

2025年05月04日25dyllove98

我很难格式化电子表格...也许你们可以帮助我。

我需要替换 aprox 中的部分公式。 1700 个细胞。

每个单元格中的原始公式遵循以下格式:

='2014-12'!$F$7 

我有兴趣用每列第一行中的单元格值替换公式的 '2014-12' 部分。请注意,每个单元格中的 $F$7 部分都会发生变化。

例如:

如您所见,电子表格的第一行包含我必须在年份正上方的单元格中编写的公式中替换的年份。

数据来自:

  • 第 5 到 96 行(并非列中的每个单元格都包含公式)
  • 第 2 至 25 列

我的第一个想法是使用 python 来实现这个......但是我无法让它与 pyoo、oosheet 或 uno。所以我来到 Excel 并试图编写一个执行以下操作的宏:

宏观思路:

  1. 对于第 i = 2 到 25 列,
  2. 获取 Cell(1, i).Value,
  3. 对于第 j = 5 到 96 行,
  4. 获取 Cell(j, i).Formula
  5. 将 Cell(j, i).Formula 中的 '2014-12' 部分替换为 Cell(1, i).Value
  6. 完成


到目前为止我的代码:

Sub replace_content_of_formula() 
 
Dim i, j As Integer 
 
For i = 2 To 25 
    year = Cells(1, i).Value 
 
    For j = 5 To 96 
        prev_formula = Cells(j, i).Formula 
        new_formula = prev_formula[:2] & year & prev_formula[9:] <<< I DONT KNOW HOW TO DO THIS 
        Cells(j, i).Select 
        ActiveCell.FormulaR1C1 = new_formula <<< I DONT KNOW HOW TO DO THIS 
 
    Next j 
Next i 
End Sub 

如有任何帮助,我将不胜感激。

Ps.: 我可以使用python 或vba。

请您参考如下方法:

您需要学习的主要内容是Mid 函数或Replace 函数的存在。修改后的代码如下:

Sub replace_content_of_formula() 
    Dim i As Integer, j As Integer 
    Dim prev_formula As String 
    Dim new_formula As String 
    Dim YearValue As String 
 
    For i = 2 To 25 
        YearValue = Cells(1, i).Value 
 
        For j = 5 To 96 
            prev_formula = Cells(j, i).FormulaR1C1 
            new_formula = Replace(prev_formula, "2014-12", YearValue) 
            'Or 
            'new_formula = Mid(prev_formula, 1, 2) & YearValue & Mid(prev_formula, 10) 
            Cells(j, i).FormulaR1C1 = new_formula 
        Next j 
    Next i 
End Sub