Here is a way to run the script by calling functions:
Public variables:
Public i As Integer 'the variable to loop down rows on Worksheets("Summary")
Public j As Integer 'the variable to loop down rows on Worksheets("Datab")
Public Areas As Range 'the range in Worksheets("Datab")
Public sh2 As Worksheet 'the Worksheets("Datab")
Public sh1 As Worksheet 'the Worksheets("Summary")
Public iLastRow As Integer 'the last row on Worksheets("Datab") [column D]
The module:
Sub Test6()
Dim ExchangeReference As String 'The name of the exchanges on "Summary"
Dim LastRowinSummary As Integer 'The last row in "Summary"
LastRowinSummary = Worksheets("Summary").Cells(9, 3).End(xlDown).Row
'LastRowinSummary will be the row number of the last row in sheet "Summary" column C
i = 9
j = 2
Do While i < LastRowinSummary + 1
ExchangeReference = Worksheets("Summary").Cells(i, 3)
Worksheets("Summary").Cells(i, 4) = SumOfExchanges(ExchangeReference)
i = i + 1
Loop
End Sub
The function:
Function SumOfExchanges(ExchangeReference As String) As Double
Dim m As Integer 'Will be used to define the number of times we want to loop to sum all data
Dim LastRowinDatab As Integer 'The last row in "Datab"
Dim FirstCell As Integer 'First cell of the range in "Datab"
Dim LastCell As Integer 'Last Cell of the range in "Datab"
Dim dIPVImpact As Double 'The sum of values in column IPVImpact
LastRowinDatab = Worksheets("Datab").Cells(2, 4).End(xlDown).Row
'LastRowinDatab will be the row number of the last row in sheet "Datab" column D
Do While j < LastRowinDatab + 1
If Worksheets("Datab").Cells(j, 4).Value = ExchangeReference Then
FirstCell = j
Exit Do
End If
j = j + 1
Loop
Do While j < LastRowinDatab + 1
If Worksheets("Datab").Cells(j, 4) = ExchangeReference And Worksheets("Datab").Cells(j + 1, 4) <> ExchangeReference Then
LastCell = Worksheets("Datab").Cells(j, 4).Row
'Had to use the ".Row" method in order to differentiate from the previous loop
Exit Do
End If
j = j + 1
Loop
For m = FirstCell To LastCell
dIPVImpact = dIPVImpact + Worksheets("Datab").Cells(m, 17).Value
Next
SumOfExchanges = dIPVImpact
End Function
Bookmarks