Changing a Worksheet Formula to a VBA formula with worksheet.function

谁说胖子不能爱 提交于 2020-01-03 03:19:07

问题


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

  1. Invalid worksheet references mws.Range(...
  2. missing quotes Range(B:B)
  3. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!