NO.1
ListNames方法是将工作表中的名称添加到单元格里的功能。
其用途也十分简单,官方解释:
从指定区域的第一个单元格位置开始,将所有未隐藏的名称的列表粘贴到工作表上。
语法:
Range.ListNames
ListNames方法除了可以看到所定义的名称,似乎也没有什么太大的作用。
不过,微软既然做了这个方法,一定有其应有的作用,具体起到什么样的作用,继续看。
NO.2
本例中有三个按钮,分别是新建名称、列出名称和清除名称。
为了更好地展示名称的一些操作方法,做这些相对完整的的名称管理。
NO.3
代码
列出名称按钮
Private Sub ShowNames()
ActiveSheet.UsedRange.Clear
Dim R As Range
Set R = ActiveSheet.Range("A1")
With R
.Value = "名称"
.RowHeight = 30
.ColumnWidth = 10
.Borders.LineStyle = 1
.Interior.Color = RGB(1, 231, 221)
.HorizontalAlignment = xlCenter
With .Offset(0, 1)
.Value = "名称范围"
.RowHeight = 30
.ColumnWidth = 50
.Borders.LineStyle = 1
.Interior.Color = RGB(1, 231, 221)
.HorizontalAlignment = xlCenter
End With
With .Offset(1, 0)
.ListNames
End With
Dim irow As Long, icol As Long
irow = Cells(65535, .Column).End(xlUp).Row - 1
icol = Cells(.Row, 256).End(xlToLeft).Column
If irow = 0 And ico = 0 Then MsgBox "当前没有名称!", vbInformation, "提示": Exit Sub
With .Offset(1, 0).Resize(irow, icol)
.RowHeight = 26
.Borders.LineStyle = 1
.Interior.Color = RGB(222, 251, 251)
.HorizontalAlignment = xlCenter
End With
End With
End Sub
可实现将活动表格的名称都列出来,很直观地看到有哪些已经定义"名称",以及名称范围。
新建名称
ClearNames
Dim i As Integer
Range("a1").Select
Dim na As Name
Dim nArr, n As Variant
nArr = Array("Names1", "Names2", "Names3", "Names4", "Names5")
With Selection
For Each n In nArr
i = i + 1
Application.Names.Add Name:=n, RefersTo:=ActiveSheet.Name & "!" & .Offset(i, 0).Address
Next n
End With
MsgBox "名称新建成功", vbInformation, "成功"
新建了5个名称,以数组形式给出名称名,或称范围分别以A1开始到A5。其中的地址范围可根据自己的需要进行修改。
清除名称
Private Function ClearNames()
Dim w As Application
Dim na
Set w = ActiveSheet.Application
For Each na In w.Names
na.Delete
Next na
End Function
清除名称将把所有名称删除了。