excel vba复制并粘贴以修复“ #REF”单元格

时间:2020-04-07 23:19:18

标签: excel vba

我正在尝试在excel 365上进行支票簿注册。我试图添加删除行(事务)的功能,但是当我运行vba代码时,它会出现以下错误:运行时错误'1004 ':工作表类的粘贴方法失败。

当我运行代码以删除一行时,余额列将填充为“ #REF”。我通过复制余额列并在删除行后将其粘贴回来来解决此问题的方法无法正常工作。余额列仍用“ #REF”填充。这是我用来复制和粘贴余额列的代码:

Sub DeleteTransactionRectangle_Click()
    Dim deletedRow

    Dim rng As Range
    Set rng = Selection

    deletedRow = rng.Row

    MsgBox (deletedRow)
    Worksheets("Register").Range("I:I").Copy 
    rng.EntireRow.Delete

    ActiveSheet.Paste Destination:=Worksheets("Register").Range("I:I")

End Sub

任何人都有使这项工作的想法。

2 个答案:

答案 0 :(得分:0)

您的“ rngg”较暗,但设置了“ rng”-两者是否应该不相同?

删除行时,似乎复制的信息从剪贴板中丢失。相反,您可以从上一行的I列复制公式,然后将其粘贴回删除的行中:

rng.EntireRow.Delete
ActiveSheet.Range("I" & deletedRow - 1).Copy
ActiveSheet.Range("I" & deletedRow).Select
ActiveSheet.Paste

答案 1 :(得分:0)

删除包含公式的行

enter image description here

提示

在设计模式下,右键单击命令按钮,然后选择Properties。将TakeFocusOnClick更改为False,以便在单击命令按钮时不会被选中(焦点),但是工作表上的选择保持不变。

公式

您的公式在删除行时被认为是错误的。您可以将其更改为:

=SUM(H$1:H2)-SUM(F$1:F2)

这是“删除列证明”。

改进代码

要学习

更改常量部分中的值以适合您的需求。

Option Explicit

Sub DeleteTransactionRectangle_Click()

    Const rowFR As Long = 2       ' First Row of Data
    Const colFR As Long = 9       ' Formula Column

    Dim rowLR As Long             ' Last Row of Data
    Dim rng As Range              ' Current Area (For Each Control Variable)
    Dim rngTransAction As Range   ' Transaction (Column) Range
    Dim rngUnion As Range         ' Union Range
    Dim rngFinal As Range         ' Intersection (Final) Range

    ' Calculate Last Row of Data.
    rowLR = Columns(colFR).Find(What:="*", LookIn:=xlFormulas, _
      SearchDirection:=xlPrevious).Row

    ' From the selection, create Union Range which only contains cells
    ' of Formula Column, which will later be compared
    ' to Transaction (Column) Range.
    For Each rng In Selection.Areas
        If Not rngUnion Is Nothing Then
            Set rngUnion = Union(rngUnion, Cells(rng.Row, colFR) _
              .Resize(rng.Rows.Count))
        Else
            Set rngUnion = Cells(rng.Row, colFR).Resize(rng.Rows.Count)
        End If
    Next

    ' Define Transaction (Column) Range.
    Set rngTransAction = Cells(rowFR, colFR).Resize(rowLR - rowFR + 1)

    ' Create Intersection (Final) Range which will 'eliminate'
    ' all 'non-valid' areas of the Selection Range. 'Non-valid' areas are
    ' the ones before First Row of Data and after Last Row of Data.
    If Not rngUnion Is Nothing Then Set rngFinal _
      = Intersect(rngUnion, rngTransAction)

    ' Delete rows of Intersection (Final) Range.
    If Not rngFinal Is Nothing Then rngFinal.EntireRow.Delete

End Sub