第一次来这里 - 太好了;)
我想做什么: 按下按钮时 - 通过在一系列单元格中使用循环来添加sumif公式。
Dim wbAdv As Workbook
Sub TranferDataRawToAdv_Click()
Set wbAdv = ThisWorkbook
'addHBL
'addOriginalHBLreq
addSumIfToCells
End Sub
Sub addSumIfToCells()
Dim Dept_Row As Long
Dim Dept_Clm As Long
Table1 = AdvData.range("L6:L20") 'Needs dynamic lookup
Dept_Row = AdvData.range("Q6").Row
Dept_Clm = AdvData.range("Q6").Column
Dim wsFunc As WorksheetFunction: Set wsFunc = Application.WorksheetFunction
For Each cl In Table1
wbAdv.Worksheets("Advisering").Cells(Dept_Row, Dept_Clm) = wsFunc.SumIf(range("L:L"), range("L" & Dept_Row), range("N:N"))
wbAdv.Worksheets("Advisering").Cells(Dept_Row, Dept_Clm + 1) = wsFunc.SumIf(range("L:L"), range("L" & Dept_Row), range("O:O"))
wbAdv.Worksheets("Advisering").Cells(Dept_Row, Dept_Clm + 2) = wsFunc.SumIf(range("L:L"), range("L" & Dept_Row), range("P:P"))
Dept_Row = Dept_Row + 1
Next cl
End Sub
如果我通过按F5运行代码 - 它可以将公式添加到单元格。但是点击它时只会添加0。
有任何帮助提示吗?
由于
答案 0 :(得分:1)
您需要在wsFunc.SumIf函数中确定要为范围寻址的工作表。
wsFunc.SumIf(sheets("????").range("L:L"), sheets("????").range("L" & Dept_Row), _
sheets("????").range("P:P"))
更新:
我刚刚注意到@JEEPED已经给出的答案作为原始帖子的评论。很抱歉重复。
答案 1 :(得分:0)
首先:感谢快速回复
我做了以下事情:
Dim wbAdv As Workbook
Sub TranferDataRawToAdv_Click()
Set wbAdv = ActiveWorkbook
'addHBL
'addOriginalHBLreq
addSumIfToCells
End Sub
Sub addSumIfToCells()
Dim Dept_Row As Long
Dim Dept_Clm As Long
Table1 = wbAdv.Worksheets("Advisering").range("L6:L1000") 'Needs dynamic lookup
Dept_Row = wbAdv.Worksheets("Advisering").range("Q6").Row
Dept_Clm = wbAdv.Worksheets("Advisering").range("Q6").Column
Dim wsFunc As WorksheetFunction: Set wsFunc = Application.WorksheetFunction
For Each cl In Table1
wbAdv.Worksheets("Advisering").Cells(Dept_Row, Dept_Clm) = wsFunc.SumIf(wbAdv.Worksheets("Advisering").range("L:L"), wbAdv.Worksheets("Advisering").range("L" & Dept_Row), wbAdv.Worksheets("Advisering").range("N:N"))
wbAdv.Worksheets("Advisering").Cells(Dept_Row, Dept_Clm + 1) = wsFunc.SumIf(wbAdv.Worksheets("Advisering").range("L:L"), wbAdv.Worksheets("Advisering").range("L" & Dept_Row), wbAdv.Worksheets("Advisering").range("O:O"))
wbAdv.Worksheets("Advisering").Cells(Dept_Row, Dept_Clm + 2) = wsFunc.SumIf(wbAdv.Worksheets("Advisering").range("L:L"), wbAdv.Worksheets("Advisering").range("L" & Dept_Row), wbAdv.Worksheets("Advisering").range("P:P"))
Dept_Row = Dept_Row + 1
Next cl
End Sub
它有效! ;)