Compiling Occurrances from a group of Cells

pages2go

New Member
Joined
Sep 2, 2004
Messages
2
I don't know if anyone can help me on this, but it was worth a try.

I am trying to take a range of cells and determine the total amount of time each piece of data occurs. Example:

Red
Blue
Red
Green
Blue
Blue
Black

Would then output in a seperate cell (With text wrap on of course) the following text:

"Red = 2, Blue = 3, Green = 1, Black = 1"

Any thoughts? I have never written a VBA script before so I have been dabling with it, but I can't make anything work. After countless hours of hardcore frustration to design a Function called CountSimilar(), and passing it as an argument the range of cells I am doing this for I5:I16, I am going crazy.

Thanks Everyone. :oops:
 

Excel Facts

Format cells as time
Select range and press Ctrl+Shift+2 to format cells as time. (Shift 2 is the @ sign).
=COUNTIF(Range,ConditionCell)

where ConditionCell refers to a cell housing a color whose occurrence in Range you want to count.
 
Upvote 0
Hi pages2go, welcome to the board. :biggrin:

If using the criteria is difficult, then the followinf UDF may be useful to you. This function returns a range of cells that match a format criteria, so the resulting range can then be used within other functions such as Sum, Count etc.

Insert the following code into a module then use the function like this where A1 is coloured red and you want to count the cells in I5:I16 that are red.

=COUNT(FORMATRNG(A1,0,I5:I16)

To insert code into a module...
1. Open the Visual Basic Editor (ALT+F11 or Tools|Macro|Visual Basic Editor from the menu)
2. Select Insert|Module from the menu
3. Paste the code in the right-hand window
4. Close the Visual Basic Editor (ALT+Q or File|Close and return to Microsoft Excel from the menu)

Code:
Public Function FORMATRNG(ByVal Criteria As Range, ByVal ComparisonType As Long, ParamArray Target() As Variant) As Range
'Created by Parry including improvements offered by Juan Pablo González & Daniel Klann
'Function returns a range that matches the format criteria. The function is designed to
'be used within other functions so is very flexible. Limited testing in XL2002.
'This function WILL NOT evaluate cells that have been formatted as a result of
'Conditional Formatting.

'***** EXPLANATION OF ARGUMENTS AND SYNTAX ***************
'CriteriaRange:  A single cell that has the desired format for comparison. The cell may be
'any cell including the cell that contains the FormatRng formula.
'ComparisonType:  Number representing type of format to evaluate. Select from the following list.
'0 = Compare Interior Colour
'1 = Compare Bold Font
'2 = Compare Italics
'3 = Compare Font Size
'4 = Compare Font Colour
'5 = Compare Font Name (Arial, Times New Roman etc)
'6 = Compare Underline
'TargetRange: Range/s to evaluate. This may be non-contiguous cells so you may select
'multiple ranges to evaluate. Separate each range with a comma.
'EG: =SUM(FORMATRNG(B1, 1, A1:A10,C1:C10)) returns a range that matches BoldFont value (ie
'True or False)in cell B1 against the cells A1:A10 & C1:C10 & sums the result. If B1 is
'Bold then the range will be those cells in A1:A10 & C1:C10 that are bold & visa versa
'if B1 isnt Bold.
'*********************************************************

    Dim c As Range, Rng As Range
    Dim Crit As Variant
    Dim Add As Boolean
    Dim vItem As Variant
    Dim rngTarget As Range

'Criteria Cell must only be one cell
    If Criteria.Cells.Count <> 1 Then Exit Function
    Application.Volatile

'Merge the target ranges into one range
    For Each vItem In Target
        If rngTarget Is Nothing Then
            Set rngTarget = vItem
        Else
            Set rngTarget = Application.Union(rngTarget, vItem)
        End If
    Next vItem

'Ignore blank cells
    Set rngTarget = Application.Intersect(rngTarget, rngTarget.Parent.UsedRange)

'Assign type of formatting to look for
    If ComparisonType = 0 Then
        Crit = Criteria.Interior.Color
    Else
        Crit = CallByName(Criteria.Font, Choose(ComparisonType, "Bold", "Italic", "Size", "Color", "Name", "Underline"), VbGet)
    End If

'Look for matches
    For Each c In rngTarget.Cells
        Add = False
        If ComparisonType = 0 Then
            If c.Interior.Color = Crit Then
                Add = True
            End If
        Else
            If CallByName(c.Font, Choose(ComparisonType, "Bold", "Italic", "Size", "Color", "Name", "Underline"), VbGet) = Crit Then
                Add = True
            End If
        End If
'Join cells that match criteria into a range
        If Add Then
            If Rng Is Nothing Then
                Set Rng = c
            Else
                Set Rng = Union(Rng, c)
            End If
        End If
    Next c
'Return range that matches criteria
    Set FORMATRNG = Rng
End Function
 
Upvote 0
I'm impressed, but perhaps a little dense on this. Or maybe I didn't explain well enough.

The problem is I can count how many times "red" occurs, but how am I going to compile a text string that consistes of colors that are added when I don't know what they are going to be? I used colors as an easy example but ultimately this will be an ever changing list of countries (with 100+ I don't really want to store them all somewhere to parse off of), and then it would have to count how many unique countries and associate each with a number of occurrances for a single text cell in the format listed "Name1 = x, Name2 = x, etc".

I figured I would have to compile an array of the unique names within the range, then count occurrances and compile that into another array, then output both arrays sequentially to display the name and the number of occurrances associated to it, but that is beyond me apparently. The problem comes down to the looping I have to do and the fact that I don't know what the text values are in the range of cells that I need to compile. So how would you compile a text string of something from a bunch of cells you have no idea of the content of, and have it count occurances of each in the process?

Sorry for my ignorance on this. Thanks for the great ideas so far.
 
Upvote 0
pages2go said:
...The problem is I can count how many times "red" occurs, but how am I going to compile a text string that consistes of colors that are added when I don't know what they are going to be? I used colors as an easy example but ultimately this will be an ever changing list of countries (with 100+ I don't really want to store them all somewhere to parse off of), and then it would have to count how many unique countries and associate each with a number of occurrances for a single text cell in the format listed "Name1 = x, Name2 = x, etc"...
Book5
ABCDEF
14
2Item0DistinctItemsCount
3Red1Red2
4Blue2Blue3
5Red Green1
6Green3Black1
7Blue   
8Blue   
9Black4  
Sheet1


Formulas...

B2 must house a 0.

B3, copied down:

=IF((A3<>"")*ISNA(MATCH(A3,$A$2:A2,0)),LOOKUP(9.99999999999999E+307,$B$2:B2)+1,"")

E1:

=LOOKUP(9.99999999999999E+307,B:B)

which is also a count of distinct items.

E3, copied down:

=IF(ROW()-ROW(E$3)+1<=$E$1,INDEX(A:A,MATCH(ROW()-ROW(E$3)+1,B:B)),"")

F3, copied down:

=IF(E3<>"",COUNTIF(A:A,E3),"")
 
Upvote 0
pages2go,

I created this UDF. You will have to manually set the cell that houses the formula to text wrap, column autofit and row autofit.
Code:
Option Base 1
Function test(myRange As Range) As String
    Dim myString As String
    Dim i As Double
    Dim x
    Dim y As Double
    Dim z As Double
    Dim myCell As Range
    Set myCell = myRange.Cells(1)
        y = WorksheetFunction.CountIf(myRange, myCell)
        ReDim x(1)
        x(1) = myCell.Value & " = " & y
    Set myCell = Nothing
    For Each myCell In myRange
        y = WorksheetFunction.CountIf(myRange, myCell)
        On Error Resume Next
        i = WorksheetFunction.Match(myCell.Value & " = " & y, x, 0)
        If Err.Number <> 0 Then
            z = UBound(x)
            ReDim Preserve x(1 To z + 1)
            x(UBound(x)) = myCell.Value & " = " & y
        End If
        On Error GoTo 0
    Next myCell
    myString = x(1)
    For i = LBound(x) + 1 To UBound(x)
        myString = myString & ", " & Chr(10) & x(i)
    Next i
    test = myString
End Function
 
Upvote 0

Forum statistics

Threads
1,215,777
Messages
6,126,838
Members
449,343
Latest member
DEWS2031

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top