每月总值超过VBA

时间:2014-04-20 17:59:47

标签: excel vba excel-vba

我已经搜索了好几个小时,因为我对VBA的了解非常有限,所以我很茫然。对于穿过顶行(行B)的几个不同的项目,我有一个“库存总计”,通过在其下面的一行上输入正数或负数以及最左边的更新日期(第1列)来更新。我有另一本书需要跟踪每个月对每个字段进行的减法。

我已经有了一个(auto_run)宏,所以我打算将它添加到它。它需要检查今天的日期,如果它是本月的第一天,那么只收取每月的所有负数(每列)的总和,并将其添加到另一本书的顶行。

我需要知道的部分是如何在VBA中获得每月的总数。

这是我用来检查今天的日期:

If Date - Day(Date) + 1 = Date - Day(Date) + 1 And Range("'Monthly Office Inventory'!A2") <> Date - Day(Date) + 1 Then

我正在考虑使用日期函数来检查上个月的第一个月和上个月末之间的值的嵌套IF检查。

请帮忙吗?

1 个答案:

答案 0 :(得分:0)

Sub Datetest()
Dim i As Integer
Dim x As Integer
Dim rng1 As Range
Dim rng2 As Range
Dim crninvbk As Worksheet
Dim mntlisbk As Worksheet
Set crninvbk = Worksheets("Current Office Inventory")
Set mntlisbk = Worksheets("sheet1")
PreviousMonth = DateAdd("m", -1, Date)
Negativemonthly = 0

For x = 2 To 23
    For i = 3 To 100
        If crninvbk.Cells(i, 1).value >= dhFirstDayInMonth And crninvbk.Cells(i, 1).value <= dhLastDayInMonth Then
            If crninvbk.Cells(i, x).value < 0 Then
            Negativemonthly = Negativemonthly + crninvbk.Cells(i, x).value
            End If
        End If
    Next i
    mntlisbk.Cells(2, x) = Negativemonthly
    MsgBox (Negativemonthly)
    Negativemonthly = 0
Next x
MsgBox (Negativemonthly)

End Sub
Function dhFirstDayInMonth(Optional dtmDate As Date = 0) As Date
    ' Return the first day in the specified month.
    PreviousMonth = DateAdd("m", -1, Date)
    dhFirstDayInMonth = DateSerial(Year(Date), _
     Month(PreviousMonth), 1)
End Function
Function dhLastDayInMonth(Optional dtmDate As Date = 0) As Date
    ' Return the last day in the specified month.
    PreviousMonth = DateAdd("m", -1, Date)
    dhLastDayInMonth = DateSerial(Year(Date), _
     Month(PreviousMonth) + 1, 0)
End Function