- 59
- 0
- 约1.77万字
- 约 18页
- 2018-08-22 发布于江苏
- 举报
Excel VBA 中的 Range 和 Cells 用法说明0
Range对象基本操作应用示例(1)
Range对象可能是VBA代码中最常用的对象,Range对象可以是某一单元格、某一单元格区域、某一行、某一列、或者是多个连续或非连续的区域组成的区域。下面介绍Range对象的一些属性和方法。- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
[示例05-01] 赋值给某单元格[示例05-01-01]Sub test1()Worksheets(Sheet1).Range(A5).Value = 22MsgBox 工作表Sheet1内单元格A5中的值为 _ Worksheets(Sheet1).Range(A5).ValueEnd Sub[示例05-01-02]Sub test2()Worksheets(Sheet1).Range(A1).Value = _Worksheets(Sheet1).Range(A5).ValueMsgBox 现在A1单元格中的值也为 _Worksheets(Sheet1).Range(A5).ValueEnd Sub[示例05-01-03]Sub test3()MsgBox 用公式填充单元格,本例为随机数公式Range(A1:H8).Formula = =Rand()End Sub[示例05-01-04]Sub test4()Worksheets(1).Cells(1, 1).Value = 24MsgBox 现在单元格A1的值为24End Sub[示例05-01-05]Sub test5()MsgBox 给单元格设置公式,求B2至B5单元格区域之和ActiveSheet.Cells(2, 1).Formula = =Sum(B1:B5)End Sub[示例05-01-06]Sub test6()MsgBox 设置单元格C5中的公式.Worksheets(1).Range(C5:C10).Cells(1, 1).Formula = =Rand()End Sub- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
[示例05-02] 引用单元格Sub Random()Dim myRange As Range设置对单元格区域的引用Set myRange = Worksheets(Sheet1).Range(A1:D5)对Range对象进行操作myRange.Formula = =RAND()myRange.Font.Bold = TrueEnd Sub示例说明:可以设置Range对象变量来引用单元格区域,然后对该变量所代表的单元格区域进行操作。- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
[示例05-03] 清除单元格[示例05-03-01]清除单元格中的内容(ClearContents方法)Sub testClearContents()MsgBox 清除指定单元格区域中的内容Worksheets(1).Range(A1:H8).ClearContentsEnd Sub[示例05-03-02]清除单元格中的格式(ClearFormats方法)Sub testClearFormats()MsgBox 清除指定单元格区域中的格式Worksheets(1).Range(A1:H8).ClearFormatsEnd Sub[示例05-03-03]清除单元格中的批注(ClearComments方法)Sub testClearComments()MsgBox 清除指定单元格区域中的批注Worksheets(1).Range(A1:H8).ClearCommentsEnd Sub[示例05-03-04]清除单元格中的全部,包括内容、格式和批注(Clear方法)Sub testClear()MsgBox 彻底清除指定单元格区域Worksheets(1).Range(A1:H8).ClearEnd Sub- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
[示例05-04] Range和CellsSub test()设置单元格区域A1:J10的边框线条样式With Worksheets(1).Range(.Cells(1, 1), _.Cell
原创力文档

文档评论(0)