您好我正在尝试运行以下代码来计算某些内容出现在工作表中的次数。
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
当我只运行代码来搜索find2时(在删除搜索find1的代码之后),我得到了39个匹配,这是正确的,但如果我运行上面的代码,我会得到15个匹配的find2。
我似乎无法弄清楚为什么会这样。
由于
答案 0 :(得分:3)
工作表/范围对象的范围不正确。一个常见的错误,以及避免依赖Select
和Activate
方法等构造的一个原因,除非另有明确说明,否则范围对象始终引用ActiveSheet
。
尝试这样做(根据Garys的建议编辑使用子程序而不是函数):
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
答案 1 :(得分:1)
答案 2 :(得分:0)
您正在使用Sheets("Recording Sheet").Select
切换到“记录表”,但您没有切换回Sheet
。所以第二个CountIf
发生在“记录表”上。