如何保留header并删除所有数据?

How to keep header and delete all data?

我试图保留第一行,remove/delete sheet 的所有数据都命名为“Main”。我的以下代码不会从名为“Main”的 sheet 中删除任何数据。

Sub clean_sheets()

'-------Clear Main Sheet all data will be removed except Header Row-----
With ActiveWorkbook.Worksheets("Main")
   Rows("2:" & Rows.Count).ClearContents
End With

'----Delete all existing worksheets after "Main" Worksheet
' and save the active workbook for next run------

Dim xWs As Worksheet

Application.ScreenUpdating = False
Application.DisplayAlerts = False
For Each xWs In Application.ActiveWorkbook.Worksheets
    If xWs.Name <> "MacroButtons" And xWs.Name <> "Main" Then
        xWs.Delete
    End If
Next
Application.DisplayAlerts = True
Application.ScreenUpdating = True

ActiveWorkbook.Save

End Sub

上面的内容是删除 header 行以外的所有数据,并删除除 sheet“主要”之外的任何其他 sheet。

我只想删除 sheet 中除 header 行之外名为“Main”的所有数据。

主要Excel数据

它应该删除除 row1 header 行之外的所有数据并调整 sheet.
的大小

试试吧。

Sub test1()
Sheets("Sheet1").Rows("2:" & Sheets("Sheet1").Rows.Count).ClearContents
End Sub


Sub test2()
Dim ws As Worksheet
Application.DisplayAlerts = False
For Each ws In Worksheets
    If ws.Name <> "Sheet1" Then ws.Delete
Next ws
Application.DisplayAlerts = True
End Sub

试试这个

Sub test1()
    Application.DisplayAlerts = FALSE
    Sheets("Sheet1").Rows("2:" & Sheets("Sheet1").Rows.Count).ClearContents
    
    Dim ws          As Worksheet
    
    For Each ws In Worksheets
        If ws.Name <> "Sheet1" Then ws.Delete
    Next ws
    Sheet1.Columns.AutoFit
    ActiveWorkbook.Save
    Application.DisplayAlerts = TRUE
    
End Sub