[英]How to run macros only the first time the excel file opens
我已经为我的 Excel 工作表编写了一些 VBA 代码。 问题是我希望它只运行一次,即当用户第一次打开它时。
如果第二次或更多次打开,我希望 excel 在不运行该 VBA 代码的情况下正常打开。 如何使用 VBA 或是否有任何 excel 功能?
简单,给工作表 2 一个特定的名称,并让宏检查该名称作为它的第一个任务,如果找到它就结束,如果没有找到它然后运行其余的代码......
在excel中的单元格中添加一个标志,每次打开excel时,宏代码都会检查该单元格中的值是否为“1”。 如果为“1”,则首次打开 excel,否则该单元格的值被更改。
以下是代码:
Sub Workbook_Open()
Worksheets("your_wsname").Activate
'to check if it the file is being opened for the first time
If Cells(100, 100).Value = "1" Then
'value is blank if opening file for the first time
'if for first time then following happens
Else
'call your methods here
'set flag value 1 in one of the methods
End If
End Sub
将您的代码存储在 XLSM 中(这是其中包含代码所必需的)。
On_Open
触发
下面的代码将每天运行一次,创建另一个工作表来记录事件,就像我在名为 Event Recording 的工作表中创建的时间线一样,然后让我的宏检查低于该特定日期的值,如果值 >0,则宏将不会执行。
Private Sub Workbook_Open()
Dim Sh As Worksheet, i As Long, Cl As Long, Cntr As Long
Set Sh = ThisWorkbook.Worksheets("Event Recording")
Cl = Sh.UsedRange.Cells.Find(What:=Date).Column
Cntr = Sh.Cells(2, Cl)
If Cntr = 0 Then
MsgBox "Hi"
End If
Sh.Cells(2, Cl) = Cntr + 1
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.