根据今天的日期更改单元格值

时间:2020-03-06 08:39:15

标签: excel vba

我以前没有做过VB for excel,但是有其他语言的经验。

我希望该人员在“今天的超额”中输入该金额,并根据日期(今天的日期)自动将该金额键入另一个单元格中。

enter image description here

1 个答案:

答案 0 :(得分:1)

用于手动输入数据的工作表结构必须将日期保留在A:A列中,并且值将输入在B:B列中

您必须打开IDE(Alt + F11)并双击工作表模块(您打算在其中手动输入数据)并在其中复制下一个代码:

Private Sub Worksheet_Change(ByVal Target As Range)
   Dim lastR As Long, rng As Range
   lastR = Range("A" & Cells.Rows.Count).End(xlUp).row
   Set rng = Range("B2:B" & lastR)
   If Not Application.Intersect(Target, rng) Is Nothing Then'the code runs only for changes in the B:B range, containing data (in A:A)
        Dim rowDate As Long, sh As Worksheet, refDate As Date, rowD As Range
        rowDate = Target.row: refDate = CDate(Target.Offset(0, -1).value)
        Set sh = Worksheets("YourSheeetToBeUpdated") 'Be carefull to change here your sheet name to be updated

        lastR = sh.Range("A" & Cells.Rows.Count).End(xlUp).row
        Set rng = sh.Range("A2:A" & lastR)
        Set rowD = rng.Find(CDate(refDate), , , xlWhole)
        If Not rowD Is Nothing Then
            rowD.Offset(0, 1).value = Target.value
        Else
            MsgBox "The date " & refDate & " could not be found in " & sh.Name
        End If
   End If
End Sub

请小心使用要更新的工作表名称。用该特定的工作表名称更改“ YourSheeetToBeUpdated”。如果您不了解某些内容,请随时询问。