I have two worksheets in an Excel 2016 (win 10) worksheet: data
and template
. Data
contains the CLASS and related data. The sheet is sorted (a-z) by CLASS. Template
contains background data with one row per class. An example of a CLASS might be oranges
, apples
, blackberries
.
I traverse the list of classes in Template
. For each class, I use AutoFilter to select a particular class on the "data" sheet and then count the number of entries with .SpecialCells(XlCellTypeVisible).Rows.count
. I save the count to the Template
sheet. The first class is filtered and counted correctly. All of the following classes are filtered correctly, but the count is zero.
Example:
"data" sheet
CLASS column (sorted a-z)
apples
apples
apples
apples
apples
blackberries
blackberries
blackberries
oranges
oranges
"Template" sheet
CLASS column
apples
blackberries
melons
oranges
Desired result:
"Template" sheet
CLASS column myCount column
apples 5
blackberries 3
melons 0
oranges 2
Actual results:
"Template" sheet
CLASS column myCount column
apples 5
blackberries 0
melons 0
oranges 0
My code is:
Sub CountAll()
Dim rng As Range
Dim myRow As Integer 'Row number in Template
Dim thisClass As String 'Class we are currently counting
Dim myCount As Integer 'Number of times thisClass is in "data"
Dim numClasses as Integer 'Set to the number of classes in "Template"
...
For myRow = 1 to numClasses
thisClass = Worksheets("template").Cells(myRow, 1).Value
Set rng = Worksheets("data").Range("A:A")
With rng
.AutoFilter Field:=1, Criterial:=thisClass
End With
myCount = rng.SpecialCells(xlCellTypeVisible).Rows.count
Worksheets("template").Cells(myRow,3).Value = myCount
ActiveSheet.showAllData 'Display all data again.
Next myRow
End Sub
This code is temporary (6-12 months) until a report generator is purchased. VBA was not my choice. I'm better with assembly, c, FORTRAN, and JAVA. Any suggestions would be greatly appreciated. I have spent about 4 hours researching this problem.