1

我要做的是遍历包含工作表名称的范围,如果单元格不为空,则将CountA函数的结果添加到 count 变量中。

所以计数变量应该等于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

我尝试了一种替代方法来遍历第二个范围,如果单元格不为空,则将变量增加 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

请帮帮我。非常感谢所有抽出时间回复的人。

4

2 回答 2

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

非常感谢大家:)

于 2013-02-15T15:27:34.697 回答
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
于 2013-02-15T15:22:35.793 回答