首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何每天将日期添加到第一个空白行

如何每天将日期添加到第一个空白行
EN

Stack Overflow用户
提问于 2020-01-20 19:09:34
回答 1查看 65关注 0票数 0

我希望每天,当我打开excel,我的excel会添加一个今天的日期到它。我有这段代码,但它不起作用,有时它能做它应该做的事情,有时它跳过一行,有什么帮助吗?

代码语言:javascript
复制
Sub Stretching()
'This procedure will run each time you open the workbook

   'Specify the required worksheet name in double quotes
    Dim ws As Worksheet
    Set ws = Sheets("Stretching")

    'Get the last row number filled with a value in Column A
    Dim lastRow As Long
    lastRow = Cells(Rows.Count, 1).End(xlUp).Row

    'Check if the last entered date is the same as the current date, if so, exit
    'You need this check to see if you close the workbook then open it on the same day
    'so that the code does not enter the same date again in a new row.
    If ws.Cells(lastRow, 1).Value = Date Then Exit Sub

    'Fill a new row in Column A with the current date
    If IsEmpty(Cells(lastRow, 1)) Then
        ws.Cells(lastRow, 1).Value = Date
    Else
        ws.Cells(lastRow, 1).Offset(1, 0).Value = Date

    End If
End Sub
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-01-20 19:20:45

关于您的代码的一些建议:

  1. 完全限定了范围,帮助您避免结果不一致。这意味着,当活动工作表与您所针对的工作表不同时,您可以运行该过程,这一行:Cells(Rows.Count, 1).End(xlUp).Row将返回与您预期不同的“最后一行”,
  2. 也尝试使用易于理解的变量名。例如,targetSheet

ws

-:

代码语言:javascript
复制
Public Sub Stretching()
    'This procedure will run each time you open the workbook

   'Specify the required worksheet name in double quotes
    Dim targetSheet As Worksheet
    Set targetSheet = ThisWorkbook.Sheets("Stretching")

    'Get the last row number filled with a value in Column A
    Dim lastRow As Long
    lastRow = targetSheet.Cells(targetSheet.Rows.Count, 1).End(xlUp).Row

    'Check if the last entered date is the same as the current date, if so, exit
    'You need this check to see if you close the workbook then open it on the same day
    'so that the code does not enter the same date again in a new row.
    If targetSheet.Cells(lastRow, 1).Value = Date Then Exit Sub

    'Fill a new row in Column A with the current date
    If IsEmpty(targetSheet.Cells(lastRow, 1)) Then
        targetSheet.Cells(lastRow, 1).Value = Date
    Else
        targetSheet.Cells(lastRow, 1).Offset(1, 0).Value = Date
    End If

End Sub
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59829520

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档