[英]Replace part of a cell formula dynamically using value of another cell
我在格式化电子表格时遇到了麻烦,也许你们可以帮助我。
我需要替换aprox中的部分公式。 1700格。
这些单元格中每个单元格中存在的原始公式遵循以下格式:
='2014-12'!$F$7
我有兴趣将公式的'2014-12'
部分替换为每个列第一行中单元格的值。 请注意, $F$7
部分在每个单元格中都会更改。
例如:
如您所见,电子表格的第一行包含我必须替换的年份,该年份必须在年份上方的单元格中编写的公式内。
数据来自:
我的第一个想法是使用python来实现这一目标...但是我无法使其与pyoo
, oosheet
或uno
。 因此,我来到Excel
并试图编写一个执行以下操作的宏:
宏观思路:
Cell(1, i).Value
, Cell(j, i).Formula
Cell(1, i).Value
替换Cell(j, i).Formula
的'2014-12'部分 到目前为止,我的代码:
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
我将不胜感激任何帮助。
附言:我可以使用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
我不在安装Windows的计算机上,但是可以在LibreOffice Calc中使用...
如果在单元格A5中写入=A$1
,它将(显然)引用A1。 如果将其复制并粘贴到工作表上,它将在B列中粘贴为=B$1
在=C$1
列中粘贴为=C$1
,依此类推。因此,它将始终查找第一行。
如果第一行是格式化的日期而不是文本,则可以使用=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")))
然后,您应该可以将此公式复制粘贴到工作表上。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.