Excel VBA:如何检索工作表中单个列中的命名单元格数?

时间:2017-01-17 21:29:06

标签: excel-vba vba excel

Sheet1中A列中的多个单元格具有指定的唯一名称。返回指定单元格的数字的sub会是什么样的?

1 个答案:

答案 0 :(得分:0)

尝试这一点,它将循环遍历工作簿中的所有命名范围,并检查它们是否与列A(或任何您定义的checkRange)相交。实际上,我很难选择特定于单个工作表的命名范围。这也将计算在A列中具有任何单元格的命名范围,但可能大于该范围。

Public Sub CountNamedRanges()     On Error Resume Next

Dim namedRangeCount As Long
Dim nameCollection As Names
Dim v As Variant
Dim n As Name
Dim nameRange As Range      'The range of the specific namedRange
Dim checkRange As Range     'The range you wish to see if it contains the named range

namedRangeCount = 0

'This is the range where we are counting named ranges
Set checkRange = ThisWorkbook.Sheets("Sheet1").Range("A:A")

Set nameCollection = ThisWorkbook.Names         'This actually didn't work when I tried to retrieve this same property for only a single worksheet
If (nameCollection.Count > 0) Then
    For Each v In nameCollection
        Set n = v
        If InStr(1, n.RefersTo, "#REF", vbTextCompare) > 0 Then        'You need this in case the named range is deleted and becomes #N/A
            Set nameRange = n.RefersToRange
            'See if the named range intersects with the check range and if so, increment the counter
            If (Application.Intersect(nameRange, checkRange)) Then
                namedRangeCount = namedRangeCount + 1
            End If
        End If
    Next v
End If

MsgBox "There are " & namedRangeCount & " named ranges in the checkRange"

End Sub