[英]Relative Range in the Row of a Formula
一個多月以來,我一直在與宏作斗爭。 目標是通過在每次列中的值更改時插入一行來按安全標識符(在 C 列中)分解數據。 之后,我想在插入的空白行中插入一個 XIRR 公式。 問題是每個證券都有不同數量的行,我無法讓行數在 XIRR 公式中變為動態。 這是我能夠放在一起的代碼:
Dim lRow As Long
Dim kRow As Long
Dim RowCount As Integer
For lRow = Cells(Cells.Rows.Count, "C").End(xlUp).Row To 2 Step -1
If Cells(lRow, "C") <> Cells(lRow - 1, "C") Then Rows(lRow).EntireRow.Insert
If Cells(lRow, "A").Value = "" Then Cells(lRow, "A").Value = "IRR"
Next lRow
For kRow = Cells(Cells.Rows.Count, "A").End(xlUp).Row To 2 Step -1
RowCount = Range(Selection, Selection.End(xlUp)).Count - 1
If Cells(kRow, "A").Value = "IRR" Then Cells(kRow, "A").Offset(0, 5).Select
Selection.Value = RowCount
ActiveCell.FormulaR1C1 = "=XIRR(R[-RowCount]C[0]:R[-1]C[0],R[-RowCount]C[-1]:R[-1]C[-1])"
Next kRow
我知道 RowCount 變量正在計算正確的行數,但 XIRR 公式不接受該變量作為行數的輸入。 每次我都會在宏的這一步得到休息,無論我嘗試多少次不同的迭代來使公式動態化。 有人可以幫助理解我做錯了什么嗎?
謝謝!
正如@BigBen 在評論中所述,您需要將 rowCount 變量構建到公式的字符串中。
ActiveCell.FormulaR1C1 = "=XIRR(R[-RowCount]C[0]:R[-1]C[0],R[-RowCount]C[-1]:R[-1]C[-1])"
變成
ActiveCell.FormulaR1C1 = "=XIRR(R[-" & RowCount & "]C[0]:R[-1]C[0],R[-" & RowCount & "]C[-1]:R[-1]C[-1])"
如果不是絕對需要,請跳過選擇步驟:
If Cells(kRow, "A").Value = "IRR" Then
Cells(kRow, "A").Offset(0, 5).FormulaR1C1 = "=XIRR(R[-RowCount]C[0]:R[-1]C[0],R[-RowCount]C[-1]:R[-1]C[-1])"
Else
Cells(kRow, "A").Offset(0, 5)=RowCount
End If
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.