2017-08-10 95 views
0

我有一個式(IF語句)我寫其是完全的功能:如何在Excel VBA中更改公式以使行爲動態?

Formula = "=IF(R3C5=""Feb"",Actuals!R133C35,IF(R3C5=""Mar"",SUM(Actuals!R133C35:R133C36),IF(R3C5=""Apr"",SUM(Actuals!R133C35:R133C37),IF(R3C5=""May"",SUM(Actuals!R133C35:R133C38),IF(R3C5=""Jun"",SUM(Actuals!R133C35:R133C39),IF(R3C5=""Jul"",SUM(Actuals!R133C35:R133C40),IF(R3C5=""Aug"",SUM(Actuals!R133C35:R133C41),IF(R3C5=""sep"",SUM(Actuals!R133C35:R133C42),IF(R3C5=""Oct"",SUM(Actuals!R133C35:R133C43),IF(R3C5=""Nov"",SUM(Actuals!R133C35:R133C44),IF(R3C5=""Dec"",SUM(Actuals!R133C35:R133C45),"""")))))))))))*1000" 

的問題是,我已經硬編碼的行爲IF函數。我引用(R3C5)的初始單元不需要更改。然而,任何時候我引用第133行,我都需要這是動態的,因爲這一行可能每個月都會改變。我需要它引用表單中最後使用的行。這些列不需要是動態的,只是行。我會怎麼做呢?

+0

見[此](https://stackoverflow.com/documentation/excel-vba/918/methods-for-finding-the-last-used-row-or-column在工作表#t = 201708101417458076783)以獲得數據的最後一行。然後將行號作爲變量傳遞給公式。 –

+0

@ScottHoltzman我結束了:Dim LR As Long'' LR = .Cells(.Rows.Count,「I」)。End(xlUp).Row'。我現在如何將它輸入if語句?喜歡這個? :.... Actuals!'LR'C35 ....? – cthallofamer

+1

'...,Actuals!R「&lRow&」C35,IF' –

回答

0

答案:

Dim LR As Long 
Dim sLongFormula$ 
Set sourceSheet = Worksheets("Actuals") 
     With sourceSheet 
     LR = .Cells(.Rows.Count, "I").End(xlUp).Row 
     sLongFormula = "=IF(Pivot!R3C5=""Feb"",Actuals!R" & LR & "C35,IF(Pivot!R3C5=""Mar"",SUM(Actuals!R" & LR & "C35:R" & LR & "C36),IF(Pivot!R3C5=""Apr"",SUM(Actuals!R" & LR & "C35:R" & LR & "C37),IF(Pivot!R3C5=""May"",SUM(Actuals!R" & LR & "C35:R" & LR & "C38),IF(Pivot!R3C5=""Jun"",SUM(Actuals!R" & LR & "C35:R" & LR & "C39),IF(Pivot!R3C5=""Jul"",SUM(Actuals!R" & LR & "C35:R" & LR & "C40),IF(Pivot!R3C5=""Aug"",SUM(Actuals!R" & LR & "C35:R" & LR & "C41),IF(Pivot!R3C5=""Sep"",SUM(Actuals!R" & LR & "C35:R" & LR & "C42),IF(Pivot!R3C5=""Oct"",SUM(Actuals!R" & LR & "C35:R" & LR & "C43),IF(Pivot!R3C5=""Nov"",SUM(Actuals!R" & LR & "C35:R" & LR & "C44),IF(Pivot!R3C5=""Dec"",SUM(Actuals!R" & LR & "C35:R" & LR & "C45),"""")))))))))))*1000" 
     End With