首页 > 解决方案 > 如何修复 VBA 复制和过去公式错误

问题描述

在此处输入图像描述

我正在尝试使用以下 VBA 代码将下面的公式插入到列的其余部分。它会将巢单元向下更改,但随后我得到一个“#NAME?” 其余单元格的错误。帮助,我做错了什么?

Private Sub CommandButton2_Click()

Dim LstRow As Long

With Sheets("sheet1")

Lastrow = .Cells(.Rows.Count, 1).End(xlUp).Row

.Range("F6:F" & Lastrow).Formula = "=IF(F5=F4,”P=”&ROW(F7)/2,F5)"
.Range("F6:F" & Lastrow).Copy
.Range("F6:F" & Lastrow).PasteSpecial xlValues
Application.CutCopyMode = False

End With

End Sub

标签: excelvba

解决方案


使用R1C1符号。更快,更容易实现。一切都与R1C1编写公式的单元格相关。

Private Sub CommandButton2_Click()

Dim LstRow As Long

With Sheets("sheet1")

    Lastrow = .Cells(.Rows.Count, 1).End(xlUp).Row

    With .Range("F6:F" & Lastrow)
        .FormulaR1C1 = "=IF(R[-1]C=R[-2]C,""P=""&R[1]/2,R[-1]C)"
        .Value = .Value
    End With

    Application.CutCopyMode = False

End With

End Sub

推荐阅读