我有以下代码,但它不起作用。
Private Sub Worksheet_Activate()
Dim l As Long
Dim LastRow As Long
Dim oWkSht As Worksheet
Dim FirstDate As Date
Dim LastDate As Date
Dim tsales As Long
FirstDate = DateSerial(Year(Date), Month(Date), 1)
LastDate = DateSerial(Year(Date), Month(Date) + 1, 0)
LastRow = Range("A100000").End(xlUp).Row
Sheets(“Main”).Range("O2").Formula = "=SumIfs(Old_Products!Z2:Z & LastRow,Old_Products!O2:O & LastRow, “ >= ” & FirstDate, Old_Products!O2:O12, “ <= ” & LastDate)+Registration!Z2:Z & LastRow"
End sub
我尝试sum
工作表注册列Z2中的所有值LastRow
以及工作表Old_Products
列O2到LastRow
中的日期是否为在当月,我希望列Z中的相应值也是计数
答案 0 :(得分:2)
如果您要使用VBA,那么您可以使用WorksheetFunction.SumIfs
,这是"=SumIfs
的VBA版本。
因此,下面的代码会将WorksheetFunction.SumIfs
中Range("O2")
的值放入&#34; Main&#34;表格,它将汇总列&#34; Z&#34;上的所有值,其中列中的日期为&#34; O&#34;介于FirstDate
和LastDate
之间。
<强>代码强>
Option Explicit
Private Sub Worksheet_Activate()
'Dim l As Long '<-- not used in this code
Dim LastRow As Long
Dim oWkSht As Worksheet
Dim FirstDate As Date
Dim LastDate As Date
'Dim tsales As Long '<-- not used in this code
Set oWkSht = Worksheets("Old_Products")
FirstDate = DateSerial(Year(Date), Month(Date), 1)
LastDate = DateSerial(Year(Date), Month(Date) + 1, 0)
LastRow = oWkSht.Range("A100000").End(xlUp).Row
Sheets("Main").Range("O2").Value = Application.WorksheetFunction.SumIfs(oWkSht.Range("Z2:Z" & LastRow), oWkSht.Range("O2:O" & LastRow), ">=" & CLng(FirstDate), oWkSht.Range("O2:O" & LastRow), "<=" & CLng(LastDate))
End Sub
修改1 :我的首选版本,因为您希望比较日期,您可以直接存储FirstDate
和LastDate
为Long
,然后之后不需要使用CLng
。
此外,添加了一个使用EoMonth
功能查找月份最后一天的选项。
代码
Option Explicit
Private Sub Worksheet_Activate()
' Dim l As Long '<-- not used in this code
Dim LastRow As Long
Dim oWkSht As Worksheet
Dim FirstDate As Long
Dim LastDate As Long
' Dim tsales As Long '<-- not used in this code
FirstDate = DateSerial(Year(Date), Month(Date), 1)
LastDate = WorksheetFunction.EoMonth(Date, 0)
Set oWkSht = Worksheets("Old_Products")
With oWkSht
LastRow = .Range("A100000").End(xlUp).Row
Sheets("Main").Range("O2").Value = Application.WorksheetFunction.SumIfs(.Range("Z2:Z" & LastRow), .Range("O2:O" & LastRow), ">=" & FirstDate, .Range("O2:O" & LastRow), "<=" & LastDate)
End With
End Sub