用名称比用 A1 样式记号更容易标识单元格区域。若要命名选定的单元格区域,请单击编辑栏左端的名称框,键入名称,再按 Enter。
下例引用了名为“MyBook.xls”的工作簿中的名为“MyRange”的单元格区域。
Sub FormatRange()
Range("MyBook.xls!MyRange").Font.Italic = True
End Sub
下例引用名为“Report.xls”的工作簿中的特定工作表单元格区域“Sheet1!Sales”。
Sub FormatSales()
Range("[Report.xls]Sheet1!Sales").BorderAround Weight:=xlthin
End Sub
若要选定命名区域,请用 GoTo 方法,该方法将激活工作簿和工作表,然后选定该区域。
Sub ClearRange()
Application.Goto Reference:="MyBook.xls!MyRange"
Selection.ClearContents
End Sub
下例显示对于活动工作簿将如何编写相同的过程。
Sub ClearRange()
Application.Goto Reference:="MyRange"
Selection.ClearContents
End Sub
下例用 For Each...Next 循环语句在命名区域中的每一个单元格上循环。如果该区域中的任一单元格的值超过 limit
的值,就将该单元格的颜色更改为黄色。
Sub ApplyColor()
Const Limit As Integer = 25
For Each c In Range("MyRange")
If c.Value > Limit Then
c.Interior.ColorIndex = 27
End If
Next c
End Sub