简体   繁体   English

公式行中的相对范围

[英]Relative Range in the Row of a Formula

I have been struggling with a macro for over a month now.一个多月以来,我一直在与宏作斗争。 The goal is to break up data by security identifier (in column C) by inserting a row every time the value in the column changes.目标是通过在每次列中的值更改时插入一行来按安全标识符(在 C 列中)分解数据。 Afterwards, I want to insert an XIRR formula in the blank row that was inserted.之后,我想在插入的空白行中插入一个 XIRR 公式。 The issue is that every security has a different amount of rows, and I cannot get the row count to become dynamic in the XIRR formula.问题是每个证券都有不同数量的行,我无法让行数在 XIRR 公式中变为动态。 Here is the code I have been able to put together:这是我能够放在一起的代码:

 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

I know the RowCount variable is counting the correct amount of rows, but the XIRR formula is not accepting the variable as an input to the row count.我知道 RowCount 变量正在计算正确的行数,但 XIRR 公式不接受该变量作为行数的输入。 I get a break at this step of the macro every time, no matter how many different iterations I try to make the formula dymanic.每次我都会在宏的这一步得到休息,无论我尝试多少次不同的迭代来使公式动态化。 Could someone please help understand what I am doing wrong?有人可以帮助理解我做错了什么吗?

Thank you!谢谢!

As stated by @BigBen in the comments, you need to build your rowCount variable into the string for your formula.正如@BigBen 在评论中所述,您需要将 rowCount 变量构建到公式的字符串中。

ActiveCell.FormulaR1C1 = "=XIRR(R[-RowCount]C[0]:R[-1]C[0],R[-RowCount]C[-1]:R[-1]C[-1])"

becomes变成

ActiveCell.FormulaR1C1 = "=XIRR(R[-" & RowCount & "]C[0]:R[-1]C[0],R[-" & RowCount & "]C[-1]:R[-1]C[-1])"

And while you're at it skip the Selection step if it's not absolutely needed:如果不是绝对需要,请跳过选择步骤:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM