如何从表中删除所有记录

时间:2013-11-06 18:23:46

标签: excel vba

我想清除我创建的excel表中的所有记录(该表只是一个已经边界的行和列的列表)。目前使用下面的代码我可以产生一点验证,其中可以删除47或更高的一行。但是,当我单击按钮时,这只会删除一行:

Sub Clear1st()

Dim iRet1 As Integer
Dim iRet2 As Integer
Dim iRet3 As Integer
Dim strPrompt1 As String
Dim strPrompt2 As String
Dim strPrompt3 As String
Dim strTitle1 As String
Dim strTitle2 As String
Dim strTitle3 As String

    Application.ScreenUpdating = False

    ActiveSheet.Unprotect

    strPrompt1 = "Only rows 47 and higher may be cleared"
    strTitle1 = "Deletion Error"
    strPrompt2 = "Are you sure you want to clear all records?"
    strTitle2 = "Clear Records Confirmation"
    strPrompt3 = "There is no recods to clear."
    strTitle3 = "Data Missing"

    If Selection.Row <= 46 Then
    iRet1 = MsgBox(strPrompt1, vbOKOnly, strTitle1)
        If iRet1 = vbOKOnly Then
       Exit Sub
        End If
    End If

    If Application.CountA(ActiveCell.EntireRow) = 0 Then
        ElseIf Selection.Row < 47 Then
    iRet3 = MsgBox(strPrompt3, vbOKOnly, strTitle3)
        If Ret3 = vbOKOnly Then
       Exit Sub
        End If
    End If
    If Selection.Row >= 47 Then
    iRet2 = MsgBox(strPrompt2, vbYesNo, strTitle2)
        If iRet2 = vbNo Then
       Exit Sub
    Else
        If iRet2 = vbYes Then

    Selection.EntireRow.Delete

    End If
        End If
            End If

    ActiveSheet.Protect DrawingObjects:=True, Contents:=True, Scenarios:=True _
        , AllowFormattingCells:=True, AllowFormattingColumns:=True, _
        AllowFormattingRows:=True, AllowSorting:=True, AllowFiltering:=True, _
        AllowUsingPivotTables:=True

    Application.ScreenUpdating = True

End Sub

我的问题是,我似乎无法想到的是,当我点击按钮时,我希望它从表中删除所有记录。

因此,如果用户点击按钮,则从列J-M之间的第47行开始,它将删除所有行。但是我怎样才能让它一次删除所有记录?就像我说的那样,表行只是边界,使它看起来像行(J2:M2),它抓住一个有边界的行,复制它并将其添加到表中。

以下是关于表格外观的截图(表格中的行数不同,但屏幕截图从47到71):

http://www.dropviewer.com/v.php?i=527a891790213.png

1 个答案:

答案 0 :(得分:0)

不确定我是否完全理解您想要的结果,但用这样的内容替换Selection.EntireRow.Delete语句应该会有所帮助:

    With ActiveSheet
       Rows("47:" & .Rows.Count).Delete
    End With