我有一个遍历X个工作表的函数,以计算满足某个条件的数量,但是我希望这个条件是可变的。
这是我的函数代码:
Function f_1(Condition As Variant, Condition_TrueFalse As Boolean, i_Start As Long, i_End As Long) As Long
f_1 = 0
For i = i_Start To i_End
Select Case Condition
Case Condition_TrueFalse
f_1 = Application.Sum(f_1, 1)
End Select
Next i
End Function
我有一个包含20个工作表的工作簿,名称分别为“ WorksheetNumber1”,“ WorksheetNumber2”,“ WorksheetNumber3”,“ WorksheetNumber4”,...,“ WorksheetNumber20”。
例如,我可能有以下子例程:
Sub(Workbook1 As Workbook)
Dim count As Long
'example A
count = f_1(IsEmpty(Workbook1.Worksheets("WorksheetNumber" & i).Cell(1,1)),False,1,10)
MsgBox(count)
'example B
count = f_1(Application.CountA(Workbook1.Worksheets("WorksheetNumber" & i).Range("$C$3:$E$5"))>0,True,1,5)
MsgBox(count)
End Sub
我有多个条件,所以我真的不想重复代码。由于代码的结构相似,所以我认为我可能可以使标准可变。
我想要的是:
当前,我在“ count = ...”行代码中遇到“下标超出范围”错误,我猜这是由于工作表中的“ i”(“ SheetNumber” & 一世)。我该如何编码才能获得想要的结果?
非常感谢您!
答案 0 :(得分:0)
提供的所有测试都可以表示为工作表公式,然后您可以执行以下操作:
Sub tester()
Debug.Print CountIt(ThisWorkbook, "A1<>""""", 1, 5)
Debug.Print CountIt(ThisWorkbook, "COUNTA(C3:E5)>0", 1, 5)
Debug.Print CountIt(ThisWorkbook, "CountRedFont(B3:B5)", 1, 5)
End Sub
Function CountIt(wb As Workbook, theTest As String, _
fromSheet As Long, toSheet As Long) As Long
Dim n As Long, i As Long
For i = fromSheet To toSheet
n = n + IIf(wb.Sheets(i).Evaluate(theTest), 1, 0)
Next i
CountIt = n
End Function
'test UDF
Function CountRedFont(rng As Range)
Dim c As Range, n As Long
For Each c In rng.Cells
If c.Font.Color = vbRed Then n = n + 1
Next c
CountRedFont = n
End Function