打开电子表格时用当前日期填充单元格 VBA

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

Populate cell with the current date when spreadsheet is opened VBA

vbaexcel-vbaexcel

提问by AlexB

How can I insert today's date in the cell when spreadsheet opens, so that if someone wants to change it then they can do it by changing it right within the cell.

如何在电子表格打开时在单元格中插入今天的日期,以便如果有人想更改它,那么他们可以通过在单元格内更改它来完成。

I have tried the following, but without much luck

我尝试了以下方法,但运气不佳

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim temp As String

    If Home.Range("_invoiceDate").Value = "" Then
        Home.Range("_invoiceDate").Value = Date
    End If
End Sub  

The cell is a named range "_invoiceDate" and worksheet is "Home"

单元格是一个命名范围“_invoiceDate”,工作表是“Home”

Thanks for your help in advance

提前感谢您的帮助

回答by Mike

For the code to run when you open the workbook, you will need to place the code in the Workbook sheet like this.

要在打开工作簿时运行代码,您需要像这样将代码放在工作簿表中。

Private Sub Workbook_Open()
    dim Home as Worksheet
    set Home = Worksheets("Home")
    Home.Range("_invoiceDate").Value = Format(Now(),"mm/dd/yyyy")  
End Sub

I believe this is what you are looking for.

我相信这就是你正在寻找的。

I tested this for switching between worksheets and it works fine.

我测试了这个在工作表之间切换,它工作正常。

Private Sub Worksheet_Activate()

Dim Home As Worksheet
Set Home = Worksheets("Home")
Home.Range("_invoiceDate").Value = Format(Now(), "mm/dd/yyyy")

End Sub

Good luck and happy coding!

祝你好运,编码愉快!