The following VBA code works perfectly. However the values found can either be positive…
- User
The following VBA code works perfectly. However the values found can either be positive or negative values. Is there a way or writing this code so that this it only totals the values found that are positive and does not include the negative values. Postive values appears as 123, negative values appear as -123.
'Loop through range A3:A18 in CTasks Specific sheet For Each cell In wsSpecific.Range("A3:A18") totalSum = 0 matchFound = False For Each matchCell In rngProviders If matchCell.Value = cell.Value Then totalSum = totalSum + matchCell.Offset(0, 3).Value matchFound = True End If Next matchCell If matchFound Then cell.Offset(0, 4).Value = totalSum End If Next cell Me.Range("E19").Calculate
- Assistant
To modify the code to only total positive values and exclude negative values, you can add an IF statement inside the inner loop that checks if the value is positive before adding it to the totalSum. Here's the updated code:
vba'Loop through range A3:A18 in CTasks Specific sheet For Each cell In wsSpecific.Range("A3:A18") totalSum = 0 matchFound = False For Each matchCell In rngProviders If matchCell.Value = cell.Value Then If matchCell.Offset(0, 3).Value > 0 Then totalSum = totalSum + matchCell.Offset(0, 3).Value matchFound = True End If End If Next matchCell If matchFound Then cell.Offset(0, 4).Value = totalSum End If Next cell Me.Range("E19").CalculateWith this modification, the code will only add positive values to the totalSum variable, excluding any negative values.
- User
How will you also write athe code to total only negative values
- Assistant
If you want to modify the code to only total negative values and exclude positive values, you can add an IF statement inside the inner loop that checks if the value is negative before adding it to the totalSum. Here's the updated code to total only negative values:
vba'Loop through range A3:A18 in CTasks Specific sheet For Each cell In wsSpecific.Range("A3:A18") totalSum = 0 matchFound = False For Each matchCell In rngProviders If matchCell.Value = cell.Value Then If matchCell.Offset(0, 3).Value < 0 Then totalSum = totalSum + matchCell.Offset(0, 3).Value matchFound = True End If End If Next matchCell If matchFound Then cell.Offset(0, 4).Value = totalSum End If Next cell Me.Range("E19").CalculateWith this modification, the code will only add negative values to the totalSum variable, excluding any positive values.