创建存档宏 Excel VBA

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18695576/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 23:13:24  来源:igfitidea点击:

Creating an Archive Macro Excel VBA

vbaexcel-vbaexcel-2007excel

提问by ASM2701

In this latest project the desire is to have a button & macro that will do the following:

在这个最新的项目中,希望有一个按钮和宏来执行以下操作:

When clicked the macro will copy all the data from the existing workbook & save it to another location. To create the copy of the workbook I will be using the following code below:

单击时,宏将从现有工作簿中复制所有数据并将其保存到另一个位置。要创建工作簿的副本,我将使用以下代码:

    Application.DisplayAlerts = False
ActiveWorkbook.SaveAs Filename:="C:\Data.xlsm"
Application.DisplayAlerts = True

This code was sourced from - http://goo.gl/t7qOyB

此代码来自 - http://goo.gl/t7qOyB

Once the copy has been archived, the data in the existing workbook must then be removed leaving all the formatting behind. How can removing the data but keeping the formatting be achieved?

存档副本后,必须删除现有工作簿中的数据,保留所有格式。如何实现删除数据但保持格式?

采纳答案by ASM2701

Use the .ClearContents()property of CellsCollection

使用Collection.ClearContents()属性Cells

Sub ClearAll()
    Dim ws As Worksheet
    For Each ws In Worksheets
        ws.Cells.ClearContents
    Next
End Sub

This code iterates through all sheets in the current workbook and deletes the values from cells keeping the formatting.

此代码遍历当前工作簿中的所有工作表,并从保持格式的单元格中删除值。

Update!

更新!

If you wanted to clear only specific range on each sheet then

如果您只想清除每张纸上的特定范围,则

Sub ClearAll()
    Dim ws As Worksheet
    For Each ws In Worksheets
        ws.Range("A1:B20").ClearContents
    Next
End Sub

This will clear only range A1:B20on each sheet.

这将只清除A1:B20每张纸上的范围。