dynamic使用另一个单元格的值replace部分单元格公式

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

我需要在aprox中replace一个公式的一部分。 1700个细胞。

每个这些单元格中存在的原始公式都遵循以下格式:

='2014-12'!$F$7 

我有兴趣用每个列的第一行中单元格的值replace公式的'2014-12'部分。 请注意, $F$7部分在每个单元格中发生更改。

例:

在这里输入图像描述

正如你所看到的,我的电子表格的第一行包含了一年中我必须replace在一年中上方的单元格中写入的公式。

数据来自:

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

我的第一个想法是使用python来实现这个…但我不能使它与pyoooosheetuno 。 所以我来到Excel ,并试图写一个macros,它会做到以下几点:

macros观理念:

  1. 对于第i列= 2到25,
  2. 得到Cell(1, i).Value
  3. 对于行j = 5至96,
  4. 得到Cell(j, i).Formula
  5. replaceCell(j, i).Formula的'2014-12'部分Cell(j, i).Formula ,with Cell(1, i).Value
  6. DONE

在这里输入图像描述


我的代码到目前为止:

 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 .:我可以使用pythonvba

您需要学习的主要内容是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 

我不是在安装Windows的计算机,但这是在LibreOffice计算…

如果你在单元格A5中写入=A$1 ,它将(明显)指向A1。 如果你复制并粘贴在你的工作表上,它将被粘贴为=B$1列中的=B$1=C$1列中的C =C$1等。因此,它总是会查找第一行。

如果第一行是格式化date而不是文本,则可以使用=Text(C$1, "YYYY-MM")将它们转换为文本以匹配表单名称。

接下来,我们可以使用Address函数将单元格的地址写入另一个表格中。

=Address(1, 1, 4, True, Text(C$1, "YYYY-MM"))将生成文本 '2015-12'!A1

 =Address(1, // the row 1, // the column 4, // absolute or relative format. A number from 1 to 4. 4 is relative row & relative column True, // A1 or R1C1 format. True is A1 Text(C$1, "YYYY-MM") // the sheet name ) 

如果我们对前两个参数使用Row()Column()函数,则Address的输出将引用另一个工作表上的同一个单元格:

=Address(Row(), Column(), 4, True, Text(C$1, "YYYY-MM"))将在单元格C5中产生'2015-12'!C5 C5。

然后,您可以通过添加Row()Column()来添加偏移量 – 希望这些偏移量对于您查找的所有单元格都是相同的!

=Address(Row() + 2, Column() + 3, 4, True, Text(C$1, "YYYY-MM"))将在单元格C5中生成'2015-12'!F7

最后,使用Indirect函数将Address的文本转换为查找:

=Indirect(Address(Row() + 2, Column() + 3, 4, True, Text(C$1, "YYYY-MM")))

然后,您应该可以将此公式复制粘贴到您的工作表上。