Worksheet.Cells 属性 (Excel)

返回表示工作表上所有单元格的 Range 对象 (而不仅仅是当前正在使用的单元格) 。

语法

expression.Cells

表达式 表示 工作表 对象的变量。

备注

Range 的默认成员将包含参数的调用转发至 Item 属性,因此,可以将行和列索引指定在紧跟 Cells 关键字之后,而不是显式调用 Item。

在不使用对象识别符的情况下,使用此属性将返回一个 Range 对象,它代表活动工作表中所有的单元格。

示例

此示例将活动工作簿的 Sheet1 上单元格 C5 的字号设置为 14 磅。

Worksheets("Sheet1").Cells(5, 3).Font.Size = 14

此示例将清除活动工作簿 Sheet1 上单元格 1 中的公式。

Worksheets("Sheet1").Cells(1).ClearContents

此示例将 Sheet1 上每个单元格的字体和字号设置为 8 磅 Arial。

With Worksheets("Sheet1").Cells.Font 
    .Name = "Arial" 
    .Size = 8 
End With

在本示例中,双击数据区域中的任何单元格可在升序和降序之间进行切换。 根据双击的单元格的列对数据进行排序。

Option Explicit
Public blnToggle As Boolean

Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
    Dim LastColumn As Long, keyColumn As Long, LastRow As Long
    Dim SortRange As Range
    LastColumn = Cells.Find(What:="*", After:=Range("A1"), SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column
    
    keyColumn = Target.Column
    
    If keyColumn <= LastColumn Then
    
        Application.ScreenUpdating = False
        Cancel = True
        LastRow = Cells(Rows.Count, keyColumn).End(xlUp).Row
        Set SortRange = Target.CurrentRegion
        
        blnToggle = Not blnToggle
        If blnToggle = True Then
            SortRange.Sort Key1:=Cells(2, keyColumn), Order1:=xlAscending, Header:=xlYes
        Else
            SortRange.Sort Key1:=Cells(2, keyColumn), Order1:=xlDescending, Header:=xlYes
        End If
    
        Set SortRange = Nothing
        Application.ScreenUpdating = True
        
    End If
End Sub

本示例查看活动工作表的 C 列,对于每个包含批注的单元格,它将批注文本放入 D 列中,并从列 C 中删除批注。

Public Sub SplitCommentsOnActiveSheet()
   'Set up your variables
   Dim cmt As Comment
   Dim rowIndex As Integer
   
   'Go through all the cells in Column C, and check to see if the cell has a comment.
   For rowIndex = 1 To WorksheetFunction.CountA(Columns(3))
      Set cmt = Cells(rowIndex, 3).Comment
      If Not cmt Is Nothing Then
      
         'If there is a comment, paste the comment text into column D and delete the original comment.
         Cells(rowIndex, 4) = Cells(rowIndex, 3).Comment.Text
         Cells(rowIndex, 3).Comment.Delete
      End If
   Next
End Sub

支持和反馈

有关于 Office VBA 或本文档的疑问或反馈? 请参阅 Office VBA 支持和反馈,获取有关如何接收支持和提供反馈的指南。