问题
currently I have a relatively complex workbook formula, which I would like to translate to a vba formula.
Currently, I wrote the following but I want it to basically evaluate the function during code execution and insert the value into the required cell.
I imagine this is some combination of worksheetfunction
but I am unsure of how to translate this
Code (doesnt work)
MWS.Cells(LastMWSR + 1, ClastMWSC).Value = WorksheetFunction.SUMIFS(mws.range(N:N),mws.Range(B:B),worksheetfunction.INDEX(mws.range(B:B),worksheetfunction.MAX(worksheetfunction.INDEX((mws.range(C:C)=MWS.Cells(LastMWSR + 1, ClastMWSC - 1))*worksheetfunction.ROW(mws.range(C:C)),0))),mws.range(C:C),MWS.Cells(LastMWSR + 1, ClastMWSC - 1))
Excel Formula
=SUMIFS($N:$N,$B:$B,INDEX($B:$B,MAX(INDEX(($C:$C=$AM41)*ROW($C:$C),0))),$C:$C,$AM41)
MWS is a worksheet
LastMWSR is the last row in the Worksheet
CLASTMWSC is the last column in the worksheet
Appreciate your thoughts
EDIT: with another attempt at the formula
回答1:
Three issues here
- Invalid worksheet references
mws.Range(...
- missing quotes
Range(B:B)
- bad bracketing
Refactored, and adding some reductionist variables
Dim mws As Worksheet
Dim wf As WorksheetFunction
Dim mwsN As Range
Dim mwsC As Range
Dim mwsB As Range
Dim mwsLast As Range
Set wf = Application.WorksheetFunction
Set mws = Worksheets("mws")
Set mwsN = mws.Range("N:N")
Set mwsC = mws.Range("C:C")
Set mwsB = mws.Range("B:B")
Set mwsLast = mws.Cells(LastMWSR + 1, ClastMWSC - 1)
mws.Cells(LastMWSR + 1, ClastMWSC).Value = _
wf.SumIfs(mwsN, mwsB, wf.Index(mwsB, wf.Max(wf.Index((mwsC = mwsLast) * wf.Row(mwsC), 0))), mwsC, mwsLast)
来源:https://stackoverflow.com/questions/50748794/changing-a-worksheet-formula-to-a-vba-formula-with-worksheet-function