Hi Experts
I have the following code but its not doing the right calculation.
Firstly, here is the VBA code
Sub CalcDiff_1()
Dim rResult As Range
Dim rWhole As Range
Dim NumOfRows As Long
Dim r As Range
Dim StartColmn As Long
Dim StartRow As Long
Sheets("Economic").Range ("E7:F20")
Set rResult = Sheets("Summary").Range("C7") 'where results will be put
Set rWhole = Range("E7:F20") 'Range with 2 columns to compare on the active sheet
'Set rWhole = Selection 'Uncomment this line if you just want to select the cells to compute
If rWhole.Columns.Count <> 2 Then Exit Sub
StartRow = rWhole.Cells(1, 1).Row
StartColmn = rWhole.Cells(1, 1).Column
NumOfRows = rWhole.Rows.Count
Set r = Cells(StartRow, StartColmn)
For n = 1 To NumOfRows
If r.Value > r.Offset(0, 1).Value Then
If ((r.Value - r.Offset(0, 1).Value) / r.Value) * 100 >= 10 Then
rResult.Value = r.Address(False, False) & ":" & r.Offset(0, 1).Address(False, False)
rResult.Offset(0, 1).Value = ((r.Value - r.Offset(0, 1).Value) / r.Value) * 100 & "% difference"
Set rResult = rResult.Offset(1, 0)
End If
ElseIf r.Offset(0, 1).Value > r.Value Then
If ((r.Offset(0, 1).Value - r.Value) / r.Offset(0, 1).Value) * 100 >= 10 Then
rResult.Value = r.Address(False, False) & ":" & r.Offset(0, 1).Address(False, False)
rResult.Offset(0, 1).Value = ((r.Offset(0, 1).Value - r.Value) / r.Offset(0, 1).Value) * 100 & "% difference"
Set rResult = rResult.Offset(1, 0)
End If
End If
Set r = r.Offset(1, 0)
Next n
End Sub
imagine two columns E and D
Say your first number is 16, and your second number is 15
How would you find the percent difference.....this would be (16-15)/15 x 100 = x%
when using the above VBA code, its not doing this.......i am trying to find a % diff of 10% in the range e7:f20.....there is a diff then putthe result in column c7 worksheet 'summary'.....
any ideas.....where i have gone wrong......or what wrong with the code....?????
by: jeffldPosted on 2008-04-07 at 07:48:14ID: 21297417
It seems to work ok when I tried your code other than the fact that I had to comment out the following line or I get an error. I also used Sheet1 and Sheet2 so that I didn't have to rename the sheets :)
Sheets("Economic").Range ("E7:F20")
I've attached my sample file. Can you see if this is doing what you expect?
Example file with VBA code