我正在为我们的机械师开发一个车队管理系统,以跟踪在车辆上执行的服务。
在A1、A2、A3中,我有“到期日期”、“需要服务”和“完成日期”的表头。
例如,它显示2018年8月10日石油变化8月13日,这与表格标题相对应。
我需要代码,当完成日期输入时,自动在表格中创建另一行,并输入石油变化,但到期日现在将是3个月外的完成日期。
发布于 2018-08-14 03:45:48
我不确定如何为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中,它应该会自动运行代码。希望这会有一点帮助!
发布于 2018-08-14 04:11:37
正如@TimWilliams提到的,每当有人在Completed Date列中输入值时,都需要使用Worksheet_Change事件来捕获。因为此事件使您可以访问已更改的单元格。您可以运行检查以确保列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 (或其他数据库解决方案),这将为您提供更多选择。
https://stackoverflow.com/questions/51829126
复制相似问题