基于完成日期的更新日期

时间:2018-08-13 19:15:04

标签: excel vba

我正在为我们的技工开发车队管理系统,以跟踪要在车辆上执行的服务。

在A1,A2,A3中,我具有截止日期,所需服务和完成日期的表头。

例如,它说2018年8月10日换油日期与相应表标题相对应的2018年8月13日。

我需要这样的代码,当输入完工日期时,该代码会在表中自动创建另一行并输入换油量,但是到期日现在将比完工日期晚3个月。

2 个答案:

答案 0 :(得分:0)

我不确定如何为vba表编写代码,因为我以前从未做过,但是我输入了一个快速宏,也许可以帮助您朝正确的方向开始。根据我的理解,您在A1,A2,A3中有三个标题,并希望根据B3中的值插入新行。这个新值将是B3中的日期,但是未来三个月。

Sub threeMonths()

Dim ws As Worksheet

Dim lrow As Long 'last row in the sheet
Dim row As Long '

Dim newDate As Date 'var to save the new date

Set ws = Sheets("Sheet1")

lrow = ws.Range("A" & ws.Rows.Count).End(xlUp).row

With ws

    For row = 3 To (2 * lrow) Step 4 'starts at three because that's the first date, doubling the amount of rows, skip forward 4

        If .Cells(row, 1).Value <> 0 Then

            newDate = DateAdd("m", 3, .Cells(row, 2).Value) 'adding three months to the date in the cell
            .Cells(row + 1, 1).EntireRow.Insert
            .Cells(row + 1, 2) = newDate

        End If

    Next row

End With

End Sub

如果按照Tim William的建议将此代码放入 Worksheet_Change 中,它应该会自动运行该代码。希望这会有所帮助!

答案 1 :(得分:0)

如@TimWilliams所述,只要有人在Worksheet_Change列中输入值,就需要使用Completed Date事件进行捕获。由于此事件使您可以访问已更改的单元格。您可以进行检查以确保C列(可能是您的完成日期所在的位置)是已更新的单元格。

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim serviceNeeded As String, completedDate As Date
    Dim nextEmptyCell As Range

    ' avoids issues where an entire row or column is selected
    If Target.Cells.Count = 1 Then
        ' check if the updated cell was Column C, and there's a value
        If Target.Column = 3 And Target.Value <> "" Then
            ' if Target = C2, we're getting service from B2, 1 column to the left
            serviceNeeded = Target.Offset(columnoffset:=-1).Value
            completedDate = CDate(Target.Value)

            Set nextEmptyCell = Target.Offset(rowoffset:=1)
            nextEmptyCell.Offset(columnoffset:=-1).Value = serviceNeeded
            nextEmptyCell.Offset(columnoffset:=-2).Value = DateAdd("m", 3, completedDate)
        End If
    End If
End Sub

当然,此代码没有考虑很多潜在的边缘情况:如果用户更改前一行的completed date值怎么办?但这足以让您入门。

需要考虑的其他事项:您可能需要考虑其他解决方案。例如,您可以在Outlook中设置重复执行的任务,该任务将在任务完成后自动重新生成固定时间。您还可以考虑使用Microsoft Access(或其他数据库解决方案),这将为您提供更多选择。