Clear contents of a WorkSheet using macro, without clearing the clipboard

徘徊边缘 提交于 2019-12-11 10:48:42

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!