vba 仅当单元格包含日期时才运行宏

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24196679/
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-12 03:26:43  来源:igfitidea点击:

Run macro only if a cell contains a date

excel-vbavbaexcel

提问by user2727453

Is this possible? In my workbook I have a macro that creates a .txt file and emails it to a static box and is called by a command button. Is it possible to edit this macro to run only if cell B1 contains a date, and, if so, how?

这可能吗?在我的工作簿中,我有一个宏,它创建一个 .txt 文件并将其通过电子邮件发送到一个静态框,并由命令按钮调用。是否可以编辑此宏以仅在单元格 B1 包含日期时运行,如果是,如何运行?

Thank you.

谢谢你。

Sub AnswerMe()
If IsDate(Range("B1").Value) Then
MsgBox "Plase enter a date in B1"
msg = "Email"
response = MsgBox(msg, vbYesNo)
If response = vbYes Then
CopyDistribute
Else
End If
End If
End Sub

回答by Moiety Design

If you want to make it that when you click the command button it only runs the code if it is a date then encapsulate the code between Sub commandbutton_click()and End Subwith

如果你想让它当您单击命令按钮它只能运行的代码,如果它是那么的日期封装之间的代码Sub commandbutton_click(),并End Sub

If IsDate(Range("B1").Value) Then
    'Code required
End If

Otherwise if you want it to start whenever you open the sheet the following will work, just change my anecdote.

否则,如果您希望它在您打开工作表时启动,以下将起作用,只需更改我的轶事即可。

Private Sub worksheet_activate()

If IsDate(Range("B1").Value) Then
    MsgBox "Sure thing honey it's a date"
End If

End Sub