Home » excel » Need assistance with excel macro- vba

Need assistance with excel macro- vba

Posted by: admin April 23, 2020 Leave a comment

Questions:

have a set of SUMIF formulas that I need to adjust frequently & the only thing I need to adjust is the 3rd part of it. The 3rd part, or sum range, columns need to be shifted over to the right by 1 column each time the macro is run.

For example, my formula can be:
=SUMIF($A$1:$A$10,$A15,!$C$1:$C$10)

  • I would like to be able to run a macro that would adjust the above
    formula so that instead of adding from Column C1:C10, it would add
    Column D1:10.
  • Then the next time I run the macro, the formula will change again to Column E and so-on.

This formula would then be dragged down to all necessary rows below with the only thing changing is the 2nd part’s row #.

Is there a simple way to accomplish this?

Thanks in advance!

Here is the VB code that I got from recording a macro that changes the 3rd part, but as of now it will only change it to that specific column whenever I run it.

ActiveCell.FormulaR1C1 = "=SUMIF('WorksheetA'!R5C1:R159C1,RC1,'WorksheetA'!RC13:R159C13)"

How to&Answers:

This code stores the number of times it has been run in a public variable LngCNt. Note that the count will be set to 0 each time the file opens

The LngCnt variable is used to increment the formula ie

first run =SUMIF($A$1:$A$10,$A15,$C$1:$C$10)
second run =SUMIF($A$1:$A$10,$A15,$D$1:$D$10)
third run =SUMIF($A$1:$A$10,$A15,$E$1:$E$10)

Public LngCnt As Long
Sub Macro2()
  ActiveCell.FormulaR1C1 = "=SUMIF(R1C1:R10C1,R[4]C1,R1C" & 3 + LngCnt & ":R10C" & 3 + LngCnt & ")"
  LngCnt = LngCnt + 1
End Sub