vba - Pass Range in Function, Sum Adjacent Cells, and Return Sum -
i have following excel table:
i want pass first column string, determine address of cells called 'lna' , 'lcamp', , sum adjacent cells 'between' 2 addresses. failed code:
function lnatolcamp(componentlist) single dim integer dim lboundaddress variant, uboundaddress variant = lbound(componentlist) ubound(componentlist) if componentlist(i, 1).value = "lna" lboundaddress = componentlist(i, 1).address.offset(0, 1) end if if componentlist(i, 1).value = "lcamp" uboundaddress = componentlist(i, 1).address.offset(0, 1) end if next lnatolcamp = application.worksheetfunction.sum(lboundaddress, ":", uboundaddress) end function
maybe there's better way?
try this:
function lnatolcamp() single dim lna range, lcamp range sheets("sheet1") set lna = .range("b:b").find("lna").offset(0, 1) set lcamp = .range("b:b").find("lcamp").offset(0, 1) if not lna nothing , not lcamp nothing _ lnatolcamp = evaluate("sum(" & .range(lna, lcamp).address & ")") end end function
edit2: dynamic needs.
function consum(rng range, str1 string, str2 string, _ optional idx long = 1) variant application.volatile '<~~ autoupdate on cell change, remove otherwise dim r1 range, r2 range set r1 = rng.find(str1, rng(1), , xlwhole) set r2 = rng.find(str2, rng(1), , xlwhole, , xlprevious) if not r1 nothing , not r2 nothing _ consum = application.sum(rng.parent.range(r1.offset(0, idx), _ r2.offset(0, idx))) else consum = cverr(xlerrvalue) end function
in second function, can select range search , specify string want search.
returns #value!
error if strings specify not found. hth.
for edit2 offset dynamic (default @ 1). sum first instance of 1st string last instance of second raised chrisneilsen.
result:
Comments
Post a Comment