问题
How do I clear the contents of a excel sheet using macro, without clearing the contents of the clipboard?
I am currently using the below code(which is called by clicking a button on the sheet), but this clears the data in the clipboard, which I have copied from other source, and want to paste in the cleared sheet
Sub clearly()
Dim ws As Worksheet
For Each ws In ThisWorkbook.Worksheets
ws.UsedRange.ClearContents
Next ws
End Sub
回答1:
which I have copied from other source, and want to paste in the cleared sheet
Why not create a temp sheet and paste the data there and then clear all the sheets. Once done copy the data from the temp sheet to the relevant sheet and delete the temp sheet?
See this (TRIED AND TESTED)
Sub clearly()
Dim ws As Worksheet, wsTemp As Worksheet
'~~> Create a Temp Sheet
Set wsTemp = Sheets.Add
'~~> Copy clipboad data to temp sheet
wsTemp.Range("A1").PasteSpecial xlPasteAll
'~~> Clear contents of all sheets except temp sheet
For Each ws In ThisWorkbook.Worksheets
If ws.Name <> wsTemp.Name Then ws.Cells.ClearContents
Next ws
'~~> Copy data from temp sheet to relevant sheet
wsTemp.Cells.Copy Sheets("Sheet1").Cells
'~~> Delete temp sheet
Application.DisplayAlerts = False
wsTemp.Delete
Application.DisplayAlerts = True
End Sub
来源:https://stackoverflow.com/questions/11727620/clear-contents-of-a-worksheet-using-macro-without-clearing-the-clipboard