在指定范围内清除工作表上的命名范围?

时间:2012-10-31 11:22:25

标签: excel vba

清除工作表中部分命名范围的最佳方法是什么?

类似的东西:

Sheets("A").Range("A1:D10").ClearNames

2 个答案:

答案 0 :(得分:2)

我不知道ClearNames,但会像这样做。样品:

Option Explicit

Sub DeleteNamedRanges()
  Dim targetWorksheet As Worksheet
  Dim targetRange As Range
  Dim nameObject As Name
  Dim namedRange As Range
  Dim unionedRange As Range

  Set targetWorksheet = Worksheets("MySheetName")
  Set targetRange = targetWorksheet.Range("A1:D10")

  For Each nameObject In ActiveWorkbook.Names
    Set namedRange = nameObject.refersToRange
    If (namedRange.Worksheet.Name <> targetWorksheet.Name) Then GoTo Continue

    Set unionedRange = Application.Union(namedRange, targetRange)
    If (unionedRange.Address = targetRange.Address) Then
      namedRange.Value = "" ' namedRange.Clear
    End If

Continue:
  Next nameObject
End Sub

答案 1 :(得分:0)

如果您要删除该区域内的名称,请执行此操作,请注意,它不仅仅从目标区域中删除了名称。因此,A1:D10内部和外部存在的范围也将被删除。

Option Explicit

Public Sub DeleteRangeNames()
    Dim wsTarget As Worksheet
    Dim rTarget As Range
    Dim nTmp As Name

    'Determine the range to clear all names from
    Set wsTarget = Worksheets("enternamehere")
    Set rTarget = wsTarget.Range("A1:D10")

    'Loop through all Names in the worksheet
    For Each nTmp In ActiveWorkbook.Names
        'Check if they overlap (if no overlap the intersection is Nothing)
        If Not (Intersect(nTmp.RefersToRange, rTarget) Is Nothing) Then
            'Delete the Name object from the workbook
            nTmp.Delete
        End If
    Next nTmp
End Sub