我正在尝试使用工作表函数sumifs的vba代码。我有两张纸,纸张1包含标准范围,而纸张2包含标准。
表1:
Group Year Cutomer Amount
A 2012 Gold 1000
B 2013 Platinum 1250
C 2012 Gold 1500
B 2012 Platinum 1750
C 2013 Gold 2000
A 2013 Platinum 2250
C 2012 Gold 2500
A 2013 Platinum 2750
B 2012 Gold 3000
Sheet 2:
2012 2013
A Gold
A Platinum
B Gold
B Platinum
C Gold
C Platinum
我的代码如下:
Sub SUMIFSTWOSHEETS()
Dim i As Variant
Dim condition As Range
For i = 2 To 7
sheet2.Cells(i, 3) = WorksheetFunction.sumifs(sheet1.Range("d2:d10"), sheet1.Range("a2:a10"), sheet2.Cells(i, 1), sheet1.Range("c2:c10"), sheet2.Cells(i, 2), sheet1.Range("B2:B10"), sheet2.Range("c2"))
sheet2.Cells(i, 4) = WorksheetFunction.sumifs(sheet1.Range("d2:d10"), sheet1.Range("a2:a10"), sheet2.Cells(i, 1), sheet1.Range("c2:c10"), sheet2.Cells(i, 2), sheet1.Range("B2:B10"), sheet2.Range("d2"))
Next i
End Sub
使用上面的代码,vba正在运行,但它只给出零作为答案。
我的回答如下:
2012 2013
A Gold 0 0
A Platinum 0 0
B Gold 0 0
B Platinum 0 0
C Gold 0 0
C Platinum 0 0
有人能帮助我吗?。
答案 0 :(得分:1)
如果我正确理解了标签展示位置,请尝试将sheet2.Range("c2")
替换为sheet2.Range("c1")
,将sheet2.Range("d2")
替换为sheet2.Range("d1")
。它应该在Sheet2
:
2012 2013
A Gold 1000 0
A Platinum 0 5000
B Gold 3000 0
B Platinum 1750 1250
C Gold 4000 2000
C Platinum 0 0
作为旁注,我不确定为什么i
需要Variant
:简单的Long
应该没问题?
答案 1 :(得分:1)
您要求的值应该是最后一个参数。因此,
sheet2.Cells(i, 3) = WorksheetFunction.sumifs(sheet1.Range("a2:a10"), sheet2.Cells(i, 1), sheet1.Range("c2:c10"), sheet2.Cells(i, 2), sheet1.Range("B2:B10"), sheet2.Range("c2"), sheet1.Range("d2:d10"))
我的问题是为什么你需要一个宏而不只是将公式放在Excel中。
答案 2 :(得分:0)
Sub sumifs_worksheet()
Dim i As Variant
Dim condition As Range
For i = 2 To 8
'Sheet2.Cells(i, 3).Value = WorksheetFunction.SumIfs(Sheet1.Range("d2:d10"), Sheet1.Range("a2:a10"), Sheet2.Cells(i, 1), Sheet1.Range("c2:c10"), Sheet2.Cells(i, 2), Sheet1.Range("B2:B10"), Sheet2.Range("c2"))
Sheet2.Cells(i, 3).Value = WorksheetFunction.SumIfs(Sheet1.Range("d2:d8"), Sheet1.Range("a2:a8"), Sheet2.Cells(i, 1), Sheet1.Range("c2:c8"), Sheet2.Cells(i, 2), Sheet1.Range("B2:B8"), Sheet2.Cells(1, 3))
Sheet2.Cells(i, 4).Value = WorksheetFunction.SumIfs(Sheet1.Range("d2:d8"), Sheet1.Range("a2:a8"), Sheet2.Cells(i, 1), Sheet1.Range("c2:c8"), Sheet2.Cells(i, 2), Sheet1.Range("B2:B8"), Sheet2.Cells(1, 4))
Next i
End Sub