2016-08-17 29 views
0

一直在學習VBA,它已經幫助了10倍與我正在工作的項目。替換特定條件一次

雖然我碰到了一個障礙。

現在我目前有一個「模板表」,裏面有公式。

它看起來是這樣的:

Name 
Date Revenue Cost profit margin 
8/08 $10,000 $5000 $5000 100% 

Total xxx  xxx xxx 

所以當我有一個新的名字添加,我複製整個「模板表」,並粘貼使用的最後一個單元下方(我循環找到最後細胞,所以這被標記爲endRow)。在8/08日期行內(收入/成本),我有一個間接公式,所以我在表格名稱8/08中查找'姓名'(我在表格中標註日期)。

我需要保持'名稱'不變,所以對於整個盒子,它的價格是20美元。當我添加新日期時,它保持$ 20美元,而其他公式隨着我插入日期而改變(IE直接向左引用日期)。

這是我一直在做的,以取代公式。唯一的問題是,如果我的模板在$ A $ 9的單元格中,並且我去替換9來說25,如果日期選項卡的公式是19,那麼它將19更改爲125.因此它將所有9更改爲25.我只是想改變$ A $ fn的公式,但是我得到一個錯誤。

fn =我的for循環來發現模板框在哪裏。所以我認爲替代原配方與我把它粘貼到

Range(Cells(endRow + 2, 2), Cells(endRow + 2, 7)).Replace What:=fn, Replacement:=endRow, SearchOrder:=xlByColumns, MatchCase:=True 

新小區所以,問題在於,如何改變$ A $ X(X是單元#),以$ A $ Y(中新的細胞#),而不是碰Ax。

For fn = 1 To 10000 
    Set networkCell = Cells(fn, 1) 
     If networkCell.Value = "New Station Template" Then 
      Range(Cells(fn, 1), Cells(fn + 5, 10)).Copy 
      Range(Cells(endRow, 1), Cells(endRow + 5, 10)).Select 
      ActiveSheet.Paste 
      Cells(endRow, 1).Value = "New Station" 
      Range(Cells(endRow + 2, 2), Cells(endRow + 2, 7)).Replace What:=fn, Replacement:=endRow, SearchOrder:=xlByColumns, MatchCase:=True 
      count = count + 1 
      Exit For 
     End If 
    Next 
+0

我已經試過: //// .Replace什麼:= 「$ A $」 與FN ///// 但是,這並不工作,我得到各種各樣 – Dan

+1

不知的錯誤如果我做了newVariable =「$ A $」&fn,而不是使用fn來替換,我使用newVariable。由於它看起來不像可以創建$ A $ fn。 – Dan

+0

是的,好主意: – cyboashu

回答

0

添加一個新變量的約束$ A $結合小區#,似乎工作比較努力結合$ A $並在小區#替換代碼。

For fn = 1 To 10000 
    Set networkCell = Cells(fn, 1) 
     If networkCell.Value = "New Station Template" Then 
      Range(Cells(fn, 1), Cells(fn + 5, 10)).Copy 
      Range(Cells(endRow, 1), Cells(endRow + 5, 10)).Select 
      ActiveSheet.Paste 
      Cells(endRow, 1).Value = "New Station" 
      oldForm = 「$A$」 & fn 
      newForm = 「$A$」 & endRow 
      Range(Cells(endRow + 2, 2), Cells(endRow + 2, 7)).Replace What:= oldForm, Replacement:= newForm, SearchOrder:=xlByColumns, MatchCase:=True 

      count = count + 1 
      Exit For 
     End If 
    Next