excel - macro to add value in cells corresponding to same category -
i new macro-vba . helpful if 1 guide me in following.
i have data-set has category name in column , in column b corresponding values. it looks this
based on category name in column a, should sum of values present in b. if cells a1:a3 belongs category "a", values present in b1:b3 should summed , corresponding rows should merged in column c , resultant sum should displayed in column c output should this
i tried code using in following way
sub main() dim long dim long ' dim sum long sum = 0 dim samerows boolean samerows = true = 1 range("a" & rows.count).end(xlup).row if strcomp(cells(i, 1), cells(i + 1, 1), vbtextcompare) samerows = false end if if samerows sum = sum + cells(i, 1).value range(cells(i, 2), cells(i + 1, 2)).merge end if samerows = true cells(i, 2).value = sum next end sub
but code wrong unable provide proper cell reference values.
it of great help, if 1 share thoughts , guide me code
trying keep close style code possible, added count of number of cells needed ensure reference top left cell in field of merged cells (as excel stores values), added few more summary instances. please try following:
sub main() dim long dim long ' dim sum long dim mergecnt long mergecnt = 0 sum = 0 dim samerows boolean samerows = true = 1 range("a" & rows.count).end(xlup).row if strcomp(cells(i, 1), cells(i + 1, 1), vbtextcompare) sum = sum + cells(i, 2).value samerows = false end if debug.print (sum) if samerows sum = sum + cells(i, 2).value range(cells(i, 3), cells(i + 1, 3)).merge mergecnt = mergecnt + 1 else: cells(i - mergecnt, 3).value = sum sum = 0 mergecnt = 0 end if samerows = true cells(i, 3).value = sum next end sub
Comments
Post a Comment