如何在 Excel 工作簿打开和退出时清除指定单元格内容?


在本文中,我们将学习如何在打开或关闭 Excel 工作簿时删除特定单元格内容。此操作可以通过 VBA 代码一次应用一个来完成。在关闭文件或打开文件时都可以。当您在工作簿的特定范围内执行了一些计算或分析,并希望在下次关闭文件或打开文件时清除这些内容时,此功能非常有用。让我们看看如何应用 VBA 代码。

在工作簿打开时清除指定单元格内容

步骤 1:以下面所示的示例数据为例。

步骤 2:在此文件中,我们将删除 C1:C5 的内容。

步骤 3:从键盘上按下 Alt+F11 键,将打开 Microsoft Visual Basic for Applications 窗口。

也可以通过如下所示的“开发工具”选项卡打开上述编辑器

步骤 4:在 Microsoft Visual Basic for Applications 窗口中,双击“项目”面板中可用的 ThisWorkbook。

步骤 5:现在复制以下 VBA 代码,并将其输入 ThisWorkbook (Code) 窗口中。

Private Sub Workbook_Open() /event to call the function when the workbook will be opened. Application.EnableEvents = False / This property is set to False to prevent the application from raising any of its events. Worksheets("Sheet1").Range("C1:C5").Value = "" / Defining the Sheet name as ‘Sheet1’ and range of cells as ‘C1:C5’ whose data to be cleared when opening the file. You may modify this as per your need. Application.EnableEvents = True / specifying whether we want events to take place when the VBA code is running or not. End Sub / end of sub.

步骤 6:输入代码后,在键盘上按下 Alt+Q 键以关闭 Microsoft Visual Basic for Applications 窗口。

步骤 7:接下来,将文件保存为“启用宏的工作簿”格式。

步骤 8:现在重新打开文件,输出结果如下所示

在工作簿退出时清除指定单元格内容

步骤 1:从键盘上按下 Alt+F11 键,将打开 Microsoft Visual Basic for Applications 窗口。

也可以通过如下所示的“开发工具”选项卡打开上述编辑器

步骤 2:在 Microsoft Visual Basic for Applications 窗口中,双击“项目”面板中可用的 ThisWorkbook。

步骤 3:现在复制以下 VBA 代码,并将其输入 ThisWorkbook (Code) 窗口中。

Private Sub Workbook_BeforeClose(Cancel As Boolean) / calling an event just before closing the file. Worksheets("Sheet1").Range("C1:C5").Value = ""/ Defining the Sheet name as ‘Sheet1’ and range of cells as ‘C1:C5’ whose data to be cleared when closing the file. You may modify this as per your need. End Sub

步骤 4:输入代码后,在键盘上按下 Alt+Q 键以关闭 Microsoft Visual Basic for Applications 窗口。

步骤 5:接下来,将文件保存为“启用宏的工作簿”格式。

步骤 6:现在关闭文件,系统将在关闭文件之前删除指定内容,并显示以下提示。

注意:在以上代码中,Sheet1 和 C1:C5 是将从中清除内容的工作表名称和单元格区域。请根据需要更改它们。

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

结论

因此,本文介绍了两种在 Excel 工作簿中清除特定单元格内容的方法。一种是在打开文件时,另一种是在关闭文件时。在使用这些方法时要小心,因为一旦数据被清除,就无法恢复。继续学习,继续探索 Excel。

更新于: 2023-08-29

954 次浏览

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告