我要做的是遍历包含工作表名称的范围,如果单元格不为空,则将CountA
函数的结果添加到count变量。
因此count变量应该等于我迭代的工作表中B9:B28
范围内的非空单元格数,但奇怪的是该值等于I范围内的非空单元格数量我正在经历(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
我尝试了另一种循环遍历第二范围的方法,如果单元格不为空,则将变量递增1,但这会产生运行时错误13类型不匹配错误。这就是我现在正在做的事情:
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
请帮帮我。非常感谢所有花时间回复的人。
答案 0 :(得分:4)
基于@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
非常感谢你们:)
答案 1 :(得分:1)
试试这个:
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