【发布时间】:2020-02-14 22:59:06
【问题描述】:
我正在编写一个自动插入公式来执行计算的代码。这些公式插入的范围不断变化,我需要使用 R1C1 公式引用。我无法弄清楚如何在第二个 For Each R1C1 公式中将“g”设置为绝对单元格引用。任何帮助深表感谢。
Sub FindRow1()
Dim t As Range
Dim c As Range
Dim d As Range
Dim e As Range
Dim f As Range
Dim g As Range
With Worksheets("Recap Sheet").Cells
Set t = .Find("Year of Tax Return", After:=.Range("A1"),
LookIn:=xlValues).Cells
Set c = .Find("12. Total Gross Annual Cash Flow", After:=.Range("A1"),
LookIn:=xlValues).Cells
Set d = .Find("15. Total Annual Cash Flow Available to Service Debt",
After:=.Range("A1"), LookIn:=xlValues)
Set e = Range(t.Offset(1, 0), c.Offset(-1, 0))
Set f = Range(c.Offset(1, 0), d.Offset(-1, 0))
Set g = c.Offset(0, 9).Cells
For Each cell In e
If cell.Value <> "" Then
cell.Offset(0, 9).FormulaR1C1 =
"=average(R[0]C[-2],R[0]C[-4],R[0]C[-6],R[0]C[-8])"
End If
Next
For Each cell In e
If cell.Value <> "" Then
'& g & in the formula below does not equal the cell location set above
cell.Offset(0, 10).FormulaR1C1 = "=R[0]C[-1]/" & g & ""
End If
Next
For Each cell In f
If cell.Value <> "" Then
cell.Offset(0, 10).FormulaR1C1 =
"=average(R[0]C[-2],R[0]C[-4],R[0]C[-6],R[0]C[-8])"
End If
Next
For Each cell In f
If cell.Value <> "" Then
cell.Offset(0, 9).FormulaR1C1 = "=R[-2]C[0]*(R[0]C[1]/100)"
End If
Next
End With
End Sub
【问题讨论】:
-
获得正确 R1C1 公式的快速方法:在工作表本身中正常输入公式。然后转到文件--> 选项--> 公式,并检查“R1C1 参考样式”。然后检查公式。如果您最初使用绝对引用,例如
=SUM($A$1),它会将其转换为 R1C1 样式的绝对引用,例如=SUM(R1C1)。通常,R#C#指的是特定的行和列(即绝对引用)。当您执行R[#]C[#]时,#是对当前单元格的相对 引用。