[英]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.