excelstreet
New Member
- Joined
- Mar 9, 2022
- Messages
- 3
- Office Version
- 2019
- Platform
- Windows
Let's assume our example data set is as follows:
Column A1:A9
10
12
14
12
10
15
20
25
20
Column B1:B9
10
10
11
11
9
9
11
11
10
I'm looking for a one cell formula/vba code that will show the maximum difference between the maximum value of a dynamically increasing range in column A1:A9 and minimum value of a dynamically decreasing range in column B1:B9.
The calculation would ideally go as follows:
Max(A1:A1) - Min(B1:B9) = 10 - 9 = 1
Max(A1:A2) - Min(B2:B9) = 12 - 9 = 3
Max(A1:A3) - Min(B3:B9) = 14 - 9 = 5
Max(A1:A4) - Min(B4:B9) = 14 - 9 = 5
Max(A1:A5) - Min(B5:B9) = 14 - 9 = 5
Max(A1:A6) - Min(B6:B9) = 15 - 9 = 6
Max(A1:A7) - Min(B7:B9) = 20 - 10 = 10
Max(A1:A8) - Min(B8:B9) = 25 - 10 = 15
Max(A1:A9) - Min(B9:B9) = 25 - 10 = 15
Maximum Difference Between These Two Dynamic Ranges = 15
Here's my attempt so far
Any help would be greatly appreciated!
Column A1:A9
10
12
14
12
10
15
20
25
20
Column B1:B9
10
10
11
11
9
9
11
11
10
I'm looking for a one cell formula/vba code that will show the maximum difference between the maximum value of a dynamically increasing range in column A1:A9 and minimum value of a dynamically decreasing range in column B1:B9.
The calculation would ideally go as follows:
Max(A1:A1) - Min(B1:B9) = 10 - 9 = 1
Max(A1:A2) - Min(B2:B9) = 12 - 9 = 3
Max(A1:A3) - Min(B3:B9) = 14 - 9 = 5
Max(A1:A4) - Min(B4:B9) = 14 - 9 = 5
Max(A1:A5) - Min(B5:B9) = 14 - 9 = 5
Max(A1:A6) - Min(B6:B9) = 15 - 9 = 6
Max(A1:A7) - Min(B7:B9) = 20 - 10 = 10
Max(A1:A8) - Min(B8:B9) = 25 - 10 = 15
Max(A1:A9) - Min(B9:B9) = 25 - 10 = 15
Maximum Difference Between These Two Dynamic Ranges = 15
Here's my attempt so far
VBA Code:
Function MaxDiff(High As Range, Low As Range) As Double
' Variable Declaration
Dim MaxRange As Range
Dim MaxValue As Double
Dim MinRange As Range
Dim MinValue As Double
Dim Max As Double
Max = 0
' Find Maximum Value
Do While i < High.Cells.Rows.Count + 1
i = i + 1
MaxRange = Range(High.Cells(1, 1).Address, High.Cells(i, 1).Address)
MaxValue = WorksheetFunction.Max(MaxRange)
MinRange = Range(Low.Cells(i, 1).Address, Low.Cells(Low.Cells.Rows.Count, 1).Address)
MinValue = WorksheetFunction.Min(MinRange)
If MaxValue - MinValue > Max Then
Max = MaxValue - MinValue
End If
Loop
MaxDiff = Max
End Function
Any help would be greatly appreciated!