Home » excel » excel – Changing a Worksheet Formula to a VBA formula with worksheet.function

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

Posted by: admin May 14, 2020 Leave a comment


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


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

How to&Answers:

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)