WorksheetFunction.CountA不能返回正确的值

我想要做的是迭代遍历包含工作表名称的范围,如果单元格不为空, CountA函数的结果添加到countvariables中。

所以计数variables应该等于工作表上我正在迭代的范围B9:B28的非空白单元格的数量,但奇怪的是,该值等于我正在经历的范围中的非空单元格的数量( sheet1!d5:d24 )。

我究竟做错了什么? 这里是我使用的代码:

 For Each c In Worksheets("Sheet1").Range("d5:d24").Cells If Not IsEmpty(c) Then count = count + WorksheetFunction.CountA(c & "!b9:b28") End If Next 

我尝试了另一种方法循环通过第二个范围,如果单元格不是空的,然后增加1variables,但这是一个运行时错误13types不匹配错误。 这就是我现在正在做的事情:

  For Each c In Worksheets("Sheet1").Range("d5:d24") If Not IsEmpty(c) Then For Each c2 In Worksheets(c).Range("b9:b28") If Not IsEmpty(c2) Then 'count = count + WorksheetFunction.CountA(c & "!b9:b28") count = count + 1 End If Next End If Next 

请帮我一下 提前感谢所有抽出时间回复的人。

基于@Peter Albert和@Peter L.的评论,终于搞定了。 正确的代码是:

 For Each c In Worksheets("Sheet1").Range("d5:d24").Cells If Not IsEmpty(c.Value) Then count = count + WorksheetFunction.CountA(c.Value & "!b9:b28") End If Next 

非常感谢你们:)

尝试这个:

 Sub CountColBForColD() Dim c As Range Dim r As Long 'row counter Dim rngB As Range Dim rngD As Range Dim lookSheet As Worksheet Set rngD = Sheets("Sheet1").Range("D5:D24") Set rngB = Range("B9:B28") r = 1 For Each c In rngD If Not IsEmpty(c) Then On Error GoTo InvalidSheetName Set lookSheet = Sheets(rngB(r).Value) On Error GoTo 0 Count = Count + WorksheetFunction.CountA( _ lookSheet.Range(rngB.Address)) c.Offset(0, 1).Value = Count r = r + 1 End If NxtC: Next Exit Sub InvalidSheetName: Err.Clear MsgBox "Sheet named in " & rngB(r).Address & " does not exist.", vbInformation Resume NxtC End Sub