2016-12-10 28 views
1

我很難格式化電子表格...也許你們可以幫助我。使用另一個單元格的值動態替換部分單元格公式

我需要在aprox中替換部分公式。 1700個細胞。

本原始公式中的每個這些細胞的尊重的格式如下:

='2014-12'!$F$7 

我感興趣的每個式柱的第一行中與所述單元格的值代替公式的'2014-12'部分。請注意,$F$7部件在每個單元中發生變化。

例:

enter image description here

正如你看到的,我的電子表格的第一行包含了一年,我必須被寫在細胞中的權一年以上公式內更換。

數據變爲從:

  • 行5〜96(未在列中的每個單元格包含公式)
  • 列2至25

我的第一個想法是使用Python要達到這個目標......但我無法使它與pyoo,oosheetuno一起工作。所以,我來到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

enter image description here


到目前爲止我的代碼:

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

+0

嗨。你能否指定* Cell Reference *如何改變? '='工作表參考「單元格參考」。 –

回答

3

您需要學習的主要內容是存在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 
2

我不是在安裝Windows的計算機上,但這是在LibreOffice Calc中工作...

如果您在單元格A5,=A$1中編寫,它將(很明顯)引用A1。如果您複製並粘貼到您的工作表上,它將被粘貼爲列B,=C$1列C中的=B$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輸出將是指相同的單元上的另一片材:

在單元格C5中=Address(Row(), Column(), 4, True, Text(C$1, "YYYY-MM"))將產生'2015-12'!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")))

然後,您應該能夠將此公式複製並粘貼在你的表。

+0

你在正確的軌道上,但公式返回一個#REF!錯誤,因爲'F7'單元格不在引號中。這工作'= INDIRECT(「'」&C $ 1&「'!F7」)',有一​​個捕獲。 OP表示,F7部分是可變的。 –

+1

好的,讓我們試試'地址'而不是'間接'... –

+1

好主意。這應該工作。 '= INDIRECT(「'」&C $ 1&「'!」&ADDRESS(7; 6; 1; 1))''。 OP應該決定'row_num'和'column_num'參數如何改變。比使用'ROWS'或'COLUMNS'作爲參數值。 –

相關問題