(晚了一天,少了一美元)
我仍在使用 excel 2003 并遇到此问题。这些宏删除旧工作表并添加新工作表。第一个宏将截断工作表,因此“Ctl-End Lastcell”是最后一个内容。第二个宏只是删除工作表并添加一个具有相同名称的新工作表,因此“Ctl-End Lastcell”为 A1。
Sub ShTrunc() ' truncate active sheet to content only
Dim sold$, snew$, rowz&, colz&, zRange As Range
' -- get old and new sheet names
sold = ActiveSheet.Name ' old sheet name
Sheets.Add
snew = ActiveSheet.Name ' new name
' -- get the "true" last row and column
' based on http://www.rondebruin.nl/win/s9/win005.htm
Sheets(sold).Activate
Set zRange = Cells.Find("*", [a1], xlFormulas, xlPart, xlByRows, xlPrevious, False)
If zRange Is Nothing Then rowz = 1 Else rowz = zRange.Row
Set zRange = Cells.Find("*", [a1], xlFormulas, xlPart, xlByColumns, xlPrevious, False)
If zRange Is Nothing Then colz = 1 Else colz = zRange.Column
' -- copy the content from old sheet, paste to new sheet
Range(Cells(1, 1), Cells(rowz, colz)).Copy ' Sheets(snew).Cells(1, 1)
Sheets(snew).Activate
ActiveSheet.Paste
' -- delete old sheet and rename new to old
Application.DisplayAlerts = False
Sheets(sold).Delete
Application.DisplayAlerts = True
Sheets(snew).Name = sold ' rename to old name
' -- the following checks if the world works as it should
If ActiveSheet.UsedRange.SpecialCells(xlCellTypeLastCell).Row <> rowz Then Stop
If ActiveSheet.UsedRange.SpecialCells(xlCellTypeLastCell).Column <> colz Then Stop
End Sub
Sub ShDelAdd() ' delete and add active sheet (to CLEAR it)
' this is a simpler version of ShTrunc if you only want to clear a sheet
Dim sold$, snew$
sold = ActiveSheet.Name
Application.DisplayAlerts = False
Sheets(sold).Delete
Application.DisplayAlerts = True
Sheets.Add
snew = ActiveSheet.Name ' new name
Sheets(snew).Name = sold ' rename to old name
' -- the following checks if the world works as it should
If ActiveSheet.UsedRange.SpecialCells(xlCellTypeLastCell).Row <> 1 Then Stop
If ActiveSheet.UsedRange.SpecialCells(xlCellTypeLastCell).Column <> 1 Then Stop
End Sub