Userform时间戳单元格当文本框更新时

时间:2018-01-25 16:08:27

标签: excel-vba timestamp userform vba excel

我有一个userform,其中有两个文本框txtCurrentStatustxtDCPreviousStatus

我希望txtCurrentStatus中的信息仅在自上次更新txtDCPreviousStatus以来已过去15天或更长时才会显示在txtCurrentStatus中。

我有以下代码:

Sub txtDCCurrentStatus_AfterUpdate() 
    dim oldDate as Date
    dim timeStamp as String
    dim numOfDaysSinceLastUpdated as Integer

    'currentRow is the current row that is being updated from another part of my code
    oldDate = CDate(Cells(currentRow, 219).Value)
    timestamp = "Last updated on " & oldDate & Chr(13) & Chr(13)
    numOfDaysSinceLastUpdated = DateDiff("d", oldDate, Date) 'Date is today 
    If (numOfDaysSinceLastUpdated > 15) Then
        Me.txtDCPreviousStatus.Value = timestamp & Me.txtDCPreviousStatus.Value
        Me.txtDCPreviousStatus.Value = Me.txtDCCurrentStatus.Value & _
        Chr(13) & Me.txtDCPreviousStatus.Value
        Else
            'Do nothing
    End If
    Cells(currentRow, 219).Value = Format(Now, "mm-dd-yyyy")
End Sub

我有两个问题:

1)如果Cells(currentRow, 219).Value = ""因为txtDCCurrentStatus从未更新过,那么我会收到一条消息

  

运行时错误'6':溢出

numOfDaysSinceLastUpdated = DateDiff("d", oldDate, Date)

2)为了解决这个问题,我将Cells(currentRow, 219).Value = Format(Now, "mm-dd-yyyy")移到最顶端。当我这样做时,文本永远不会移动到txtDCPreviousStatus,因为日期会在我做出更改时自动更改为今天,所以它不会超过15天。

基本上,我是:

  • 加入oldDate,日期txtDCCurrentStatus上次更新

  • 检查txtDCCurrentStatus更新后是否已过去15天,方法是oldDate - Date,然后将其放入numOfDaysSinceLastUpdated

  • 如果是,我会将txtDCCurrentStatus的内容移至txtDCPreviousStatus
  • 立即保存txtDCCurrentStatus正在更新为Cells(currentRow, 219).Value = Format(Now, "mm-dd-yyyy")
  • 的新日期

我有办法解决这两个问题吗?

1 个答案:

答案 0 :(得分:0)

感谢@ScottHoltzman回答。我解决了我的问题

我在Sub的开头添加了以下内容并且有效

if oldDate = Empty then 
   Me.txtDCPreviousStatus.Value = ""
Else ...

我遇到的问题是,起初我正在检查if oldDate = ""。即使oldDate为空,oldDateDate,当它为空时,也会打印为"12:00:00 AM""" <> "12:00:00 AM",因此我必须检查它是否为{ {1}}