跨列的宏插入公式

时间:2017-07-13 16:30:27

标签: excel-vba vba excel

我正在尝试根据A列中的值在所有列中插入一个公式(B列到最后一列包含数据)。

以下是我到目前为止:

Sub Insert_Falldown_Ratio_Formula()
Dim Rng As Range
Dim lRow As Long
Dim lLastRow As Long


lLastRow = Cells(Rows.Count, "A").End(xlUp).Row - 1
lastcolumn = Cells(1, Columns.Count).End(xlToLeft).Column

For lRow = lLastRow To 2 Step -1

    If Cells(lRow, "A").Value = "Falldown Ratio"
        Set Rng = Range("B" & (1Row) & ":" & lastcolumn)
        Rng.FormulaR1C1 = "=IF(LEFT(RC[-1],2)=""45"",""45'"",IF(RIGHT(RC[-1],1)=""Q"",""40'HC"",LEFT(RC[-1],2)&""'""))"

    End If
Next lRow
End Sub

非常感谢任何帮助!谢谢!

1 个答案:

答案 0 :(得分:0)

一些事情。 (1)您在下一行的If行(2)上错过了一个然后您1Row而不是lRow和(3)您正在复制而不是跨越。

Sub Insert_Falldown_Ratio_Formula()

Dim Rng As Range
Dim lRow As Long
Dim lLastRow As Long, lastcolumn As Long

lLastRow = Cells(Rows.Count, "A").End(xlUp).Row - 1
lastcolumn = Cells(1, Columns.Count).End(xlToLeft).Column

For lRow = lLastRow To 2 Step -1
    If Cells(lRow, "A").Value = "Falldown Ratio" Then
        Set Rng = Range(Cells(lRow, "B"), Cells(lRow, lastcolumn))
        Rng.FormulaR1C1 = "=IF(LEFT(RC[-1],2)=""45"",""45'"",IF(RIGHT(RC[-1],1)=""Q"",""40'HC"",LEFT(RC[-1],2)&""'""))"
    End If
Next lRow

End Sub