与月初和今天日期相关的范围金额之和

时间:2014-01-16 08:16:35

标签: excel vba date

我写了这段代码,但它给出了一个错误。你能帮我纠正一下吗?我在excel中有两列:一列显示日期(每天,一个接一个),因此列中的最后一个日期是“昨天”,第二列显示相关金额。我需要通过VBA编写一个公式,计算从月初到最后一行(最后一个日期,即“昨天”)的金额之和。正如您可能所做的那样,每个月的月初变化,最后一个日期每天都在变化。 - 非常感谢你提前!

Dim x As Long
x = Month(Workbooks("Reports.xlsm").Worksheets("MACRO").Cells(2, 3))
Range("F64").Formula = "=Sum(" & Range(Cells(Worksheets("A").Cells(Rows.Count, 4).End(xlUp).Row, 4), Cells(Worksheets("A").Cells(Rows.Count, 4).End(xlUp).Row - x, 4))

2 个答案:

答案 0 :(得分:0)

昨天是Day(Now-1)。所以:

x = Day(Now-1)-1

答案 1 :(得分:0)

这是一种查找当月第一天和昨天行的方法。

Sub FindYesterdayAnd1stDayofMonth()

' Turn Off screenupdating and calc to speed up code
Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False

Dim wS As Worksheet
Set wS = ActiveSheet

Dim rFound As Range
Dim rS%, rE%

Dim M As Integer, Y As Integer


' Find 1st day of current month
M = Month(Now - 1)
Y = Year(Now - 1)

' Look in column A. Using a Range object to do some error checking when it doesn't work
Set rFound = wS.Columns(1).Find(What:=DateSerial(Y, M, 1), LookIn:=xlValues)

If rFound Is Nothing Then
    MsgBox "Date '" & DateSerial(Y, M, 1) & "' not found"
Else
    rS = rFound.Row
End If



' Find yesterday
Set rFound = wS.Columns(1).Find(What:=Date - 1, LookIn:=xlValues)

If rFound Is Nothing Then
    MsgBox "Date '" & Date - 1 & "' not found"
Else
    rE = rFound.Row
End If


' Turn updating and calc back on
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True


End Sub