在函数中多次使用CountIf不能按预期方式工作
您好,我正在尝试运行下面的代码来计算出现在工作表中的次数。
Sub test() ' passes in what sheet (Sheet1) to search and which row (5) to write the results dummy = CountExample("Sheet1", 5) End Sub Function CountExample(Sheet As String, RowPopulate As Integer) Sheets(Sheet).Select ' Selects the appropriate sheet to search through Dim tmp As Integer ' Search for find1 tmp = Application.WorksheetFunction.CountIf(Cells, "find1") Sheets("Recording Sheet").Select Range("C" & RowPopulate).Value = tmp ' Update and write the value in C5 tmp = 0 'this does not seem to do anything ' something wrong with this one find2 should have 39 matches not 15 ' Search for find2 tmp = Application.WorksheetFunction.CountIf(Cells, "find2") Sheets("Recording Sheet").Select Range("E" & RowPopulate).Value = tmp ' Update and write the value in E5 End Function
当我只是运行代码来searchfind2(在删除searchfind1的代码之后),我得到了39个匹配,这是正确的,但是如果我运行上面的代码,我得到15匹配find2。
我似乎无法弄清楚为什么会发生这种情况。
谢谢
您的工作表/范围对象的范围不正确。 一个常见的错误,也是避免依赖像Select
和Activate
方法这样的结构的一个原因,除非另外明确指出,范围对象总是指ActiveSheet
。
试试这个(编辑每Garys的build议使用一个子例程,而不是一个函数):
Sub test() ' passes in what sheet (Sheet1) to search and which row (5) to write the results CountExample "Sheet1", 5 End Sub Sub CountExample(Sheet As String, RowPopulate As Integer) ' Selects the appropriate sheet to search through Dim tmp As Integer Dim ws as Worksheet Dim wsRecord as Worksheet Set ws = Worksheets(Sheet) Set wsRecord = Worksheets("Recording Sheet") ' Search for find1 tmp = Application.WorksheetFunction.CountIf(ws.Cells, "find1") wsRecord.Range("C" & RowPopulate).Value = tmp ' Update and write the value in C5 tmp = 0 'this does not seem to do anything ' something wrong with this one find2 should have 39 matches not 15 ' Search for find2 tmp = Application.WorksheetFunction.CountIf(ws.Cells, "find2") wsRecord.Range("E" & RowPopulate).Value = tmp ' Update and write the value in E5 End Sub
- 你需要一个Sub而不是一个Function,因为你想改变一组单元而不是返回一个单一的值
您正在使用Sheets("Recording Sheet").Select
切换到“logging表格”,但不切换回Sheet
。 所以第二个CountIf
发生在“logging表”上。