VBA:如何检查细胞范围?

时间:2013-01-21 10:54:36

标签: excel-vba vba excel

我有一个名为Book.a的单元名称,如果单元格在一个范围内(if),我必须检查B1:I10条件。如何执行此操作? 我为此尝试了“交叉”方法但对我没有用。 请提出一些答案。

2 个答案:

答案 0 :(得分:1)

这是你在尝试的吗?

Option Explicit

Sub Sample()
    Dim rng As Range

    With Sheets("Sheet1")
        On Error Resume Next
        Set rng = Application.Intersect(.Range("Book.a"), .Range("B1:I10"))
        On Error GoTo 0

        If Not rng Is Nothing Then
            MsgBox "Range `Book.a` is a part of `B1:I10`"
        Else
            MsgBox "Range `Book.a` not found or is not a part of `B1:I10`"
        End If
    End With
End Sub

答案 1 :(得分:0)

似乎无法在范围内搜索命名范围。所以我回复了我的评论。 您可以尝试的是:对于每个命名范围,例如book.a,您可以检查其地址intersect是否为给定的主要范围 ..

Dim objName As Name
Dim mainRange as Range

Sheet1.Unprotect
Set mainRange = ActiveWorkbook.Sheets(1).Range("B1:I10")
For Each objName In ActiveWorkbook.Names
    strName = objName.Name
    If InStr(1, strName, "book.a", vbTextCompare) > 0 Then
      If Intersect(objName.Address, mainRange) Is Nothing then
        '-- not within
      Else
        '-- within
      End If
    End If
Next
Sheet1.Protect