monkthemighty
monkthemighty

Reputation: 135

How do I count the number of non-zeros in excel?

I am trying to make a macro that will go through a whole workbook and count the number of days a employee worked. The sheets have the work broken out in days so all T have to find is the days that are not zero. I have tried to use COUNTIF(A11:A12,">0") and I get the error Expected : list separator or ). I am using a For Each loop to work through the sheets. I would like to put all the information on a new sheet at the end of the workbook with the name of the employee and the days worked. I am very new to visual basic but am quite good with c#.

I now have gotten this far

Option Explicit

Sub WorksheetLoop2()
    ' Declare Current as a worksheet object variable.
    Dim Current As Worksheet
    Dim LastColumn As Integer

    If WorksheetFunction.CountA(Cells) > 0 Then
    ' Search for any entry, by searching backwards by Columns.
        LastColumn = Cells.Find(What:="*", After:=[A1], _
        SearchOrder:=xlByColumns, _
        SearchDirection:=xlPrevious).Column
    End If

    ' Loop through all of the worksheets in the active workbook.
    For Each Current In Worksheets
        Current.Range("A27") = Application.WorksheetFunction.CountIf(Current.Range(Cells(11, LastColumn), Cells(16, LastColumn)), ">0")
        Current.Range("A28") = Application.WorksheetFunction.CountIf(Current.Range("Al17:Al22"), ">0")
    Next
End Sub

When I run this I get an error saying method range of object'_worksheet' failed. I also haven't been able to find a way to get the information all on the summary sheet.

Upvotes: 0

Views: 10151

Answers (1)

Scott Holtzman
Scott Holtzman

Reputation: 27249

VBA Solution, in light of your last comment above.

Good VBA programming practice entails always using Option Explicit with your code, that way you know when you don't have variables declared correctly, or, sometimes, if code is bad! In this case you would have picked up that just writing A27 does not mean you are returning the value to cell A27, but rather just setting the value you get to variable A27. Or maybe you wouldn't know that exactly, but you would find out where your problem is real quick!

This code should fix it for you:

Option Explicit

Sub WorksheetLoop2()

'Declare Current as a worksheet object variable.
Dim Current As Worksheet

' Loop through all of the worksheets in the active workbook.
For Each Current In Worksheets
    Current.Range("A27") = Application.WorksheetFunction.CountIf(Current.Range("A11:A12"), ">0")
Next

End Sub

In case it helps, Non-VBA solution:

Assuming you have a Summary sheet and each employee on a separate sheet, with days in column A and hours worked in column B, enter formula in formula bar in B1 of Summary and run down the list of names in column A.

Sheet

Upvotes: 1

Related Questions