Excel/Need help in Macros
Expert: Stuart Resnick - 7/3/2009
Question
QUESTION: AA BB CC
A1 61B 1
A2 61B 1
A3 61B 1
3<-- Addition
A4 71C 2
A5 71C 2
A6 71C 2
6<-- Addition
I have a code which segregates the Data in the column BB when it encounters unique value
and iserts 2 blank rows.
I am looking forward to modify the code which will Sum the Values in the column CC and would
display them in the inserted row for each type of unique value. ( shown by "Addition")
Can you help me to solve the same.
Please find the code below and the image attached for your ready reference.
Thanks |Ankit Shah |Peoplesoft Consultant |India.
Working Code:
-------------
Sub InsertingRows()
Dim R As Range, enc As Boolean, I As Integer
Set R = ActiveSheet.Range("A1:C100")
I = R.Rows.Count
For I = 3 To 40
If R.Cells(I, 2) <> R.Cells(I - 1, 2) Then
R.Cells(I, 2).Select
ActiveCell.EntireRow.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
ActiveCell.EntireRow.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Cell(I, 2).Value = "61B"
I = I + 2
End If
Next I
End Sub
IMAGE: Macros Prob
ANSWER: Sub insertAndSum()
Dim insertAbove As Range, rngToSum As Range
Dim rngResult As Range
Set insertAbove = Range("B2")
Do
Do
Set insertAbove = insertAbove.Offset(1)
Loop Until insertAbove <> insertAbove.Offset(-1)
insertAbove.Range("a1:a2").EntireRow.Insert
Set rngResult = insertAbove.Offset(-2, 1)
Set rngToSum = Range(rngResult.Offset(-1).End(xlUp), _
rngResult.Offset(-1))
rngResult.Formula = "=SUM(" & rngToSum.Address & ")"
Loop Until insertAbove = ""
End Sub
---------- FOLLOW-UP ----------
QUESTION: Hi Stuart i am very much impressed by your work. The code is wonderful and is working absolutely fine.
I require the macro for a important report which i was not supposed to expose but after running your code i am so amazed that i got special approval to show you the report.
Right now the code is adding a row adjacent to the column BB can the code be modified to sum some other columns too.
Please find the Image attached for clear understanding.
Thanks a lot.
Yor a are a genius!
AnswerTo sum cols T, V, X, Z:
Sub insertAndSum()
Dim insertAbove As Range, rngToSum As Range
Dim rngResult As Range
Set insertAbove = Range("s2")
Do
Do
Set insertAbove = insertAbove.Offset(1)
Loop Until insertAbove <> insertAbove.Offset(-1)
insertAbove.Range("a1:a2").EntireRow.Insert
Set rngResult = insertAbove.Offset(-2, 1)
Set rngToSum = Range(rngResult.Offset(-1).End(xlUp), _
rngResult.Offset(-1))
rngResult.Formula = "=SUM(" & rngToSum.Address(False, False) & ")"
rngResult.Copy
ActiveSheet.Paste rngResult.Offset(0, 2)
ActiveSheet.Paste rngResult.Offset(0, 4)
ActiveSheet.Paste rngResult.Offset(0, 6)
Application.CutCopyMode = False
Loop Until insertAbove = ""
End Sub