如何清除除指定单元格以外的所有工作表内容

时间:2016-01-28 02:27:14

标签: excel vba excel-vba

我有一个工作表,我的数据很少,我创建了一个用于清除数据的按钮。我写的当前代码将清除从“E2”Cell开始到工作表末尾的所有数据。 我在“R2”单元格中有一个数据,我不想清楚。 有没有办法达到上述要求(从'E2'删除到工作表的其余部分,但不清除'R2'单元格的内容。)

以下是代码:

  Private Sub CommandButton25_Click()
  Range("E2:XFD1048576").ClearContents  ' but I don't want R2 cell to be Cleared
  End Sub()

2 个答案:

答案 0 :(得分:2)

Private Sub CommandButton25_Click()
  temp = Range("R2").Value
  Range("E2:XFD1048576").ClearContents
  Range("R2").Value = temp
End Sub

答案 1 :(得分:1)

Private Sub CommandButton25_Click()
    Dim tableRange As Range: Set tableRange = Range("E2:XFD1048576")
    Dim IgnoreCells As Range: 
Set IgnoreCells = Application.Union(IgnoreCells, tableRange.Range("R2"))
    Dim xlCell As Range

    Application.ScreenUpdating = False
    Application.Calculation = xlCalculationManual
    Application.Iteration = False
    For Each xlCell In tableRange.Cells
        If Application.Intersect(xlCell, IgnoreCells) Is Nothing Then
            Call xlCell.ClearContents
        End If
        DoEvents
    Next

    Application.Iteration = True
    Application.ScreenUpdating = True
    Application.Calculation = xlCalculationAutomatic

End Sub