Ranges and Cells
快速指南 Ranges and Cells
Function | Takes | Returns | Example | Gives |
---|---|---|---|---|
Range | cell address | multiple cells | .Range(“A1:A4”) | $A$1:$A$4 |
Cells | row, column | one cell | .Cells(1,5) | $E$1 |
Offset | row, column | multiple cells | Range(“A1:A2”) .Offset(1,2) | $C$2:$C$3 |
Rows | row(s) | one or more rows | .Rows(4) .Rows(“2:4”) | $4:$4 $2:$4 |
Columns | column(s) | one or more columns | .Columns(4) .Columns(“B:D”) | $D:$D $B:$D |
一般來說,您使用 Cells 主要做三件事 從單元格中讀取。
- Read from a cell.
- Write to a cell.
- Change the format of a cell.
在下面的代碼中,我們要求用戶指定列號。 使用單元格使我們可以靈活地為列使用可變數字。
Public Sub WriteToColumn()
Dim UserCol As Integer
' Get the column number from the user
UserCol = Application.InputBox(" Please enter the column...", Type:=1)
' Write text to user selected column
Sheet1.Cells(1, UserCol).Value2 = "John Smith"
End Sub
在上面的示例中,我們在列中使用數字而不是字母。 要在此處使用 Range 需要我們將這些值轉換為字母/數字單元格引用,例如 “C1”。 使用 Cells 屬性允許我們提供行號和列號來訪問單元格。 有時您可能希望使用行號和列號返回多個單元格。 下一節將向您展示如何執行此操作。