Home / User Contributed Macros / Increment counter if present else add it to table

Increment counter if present else add it to table


The following macro increments the count in Column E, If the value in Range 'A1' is present in Range(D1:D100); Else the value is added in Column D
  1. Public Sub addToTable()
  2.  
  3.     Dim searchItem as String
  4.     searchItem = Range("A1")    'Input Range
  5.  
  6.     Dim searchRegion,count as Range
  7.     Set searchRegion = Range("D1:D100")      'Table Range
  8.  
  9.     Dim nextEmptyRow as Integer
  10.  
  11.     For each cell in searchRegion
  12.         If(ucase(cell.value) = ucase(searchItem))    Then

  13.         'Increment the count if the value is present and exit
  14.             set count = Cells(cell.row, cell.column+1)           
  15.             count.value = count.value + 1

  16.             Exit Sub
  17.         End If
  18.     Next cell
  19.  
  20.     nextEmptyRow = searchRegion.End(xlDown).Row
  21.  
  22.     'Inserting new value to the table if the value is not present    
  23.     cells(nextEmptyRow+1,1).EntireRow.Insert
  24.     cells(nextEmptyRow+1, searchRegion.column).value = searchItem
  25.     cells(nextEmptyRow+1, searchRegion.column+1).value = 1
  26.  
  27. End Sub



     RSS of this page