這些範例說明如何選擇所使用的範圍,其中包含不含資料的格式化儲存格,以及如何選擇包含實際資料的儲存格的資料範圍。
範例程式碼提供者: Tom Urtis,Atlas Programming Management
選擇所用範圍
此範例展示了如何利用工作表物件的 UsedRange 屬性及範圍物件的Select 方法,選擇目前工作表中包含格式化且不包含資料的儲存格的已使用範圍。 接著它會顯示該範圍的地址給使用者。
Sub SelectUsedRange()
ActiveSheet.UsedRange.Select
MsgBox "The used range address is " & ActiveSheet.UsedRange.Address(0, 0) & ".", 64, "Used range address:"
End Sub
從 A1 格子開始選擇資料範圍
此範例展示了如何在目前資料表中從儲存格 A1 開始選擇資料範圍,並向使用者顯示該範圍的位址。 資料範圍不包含格式化但不包含資料的儲存格。 為了取得資料範圍,這個範例會利用 Range 物件的 Find 方法找到最後一列和最後一欄包含實際資料。
Sub SelectDataRange()
Dim LastRow As Long, LastColumn As Long
LastRow = Cells.Find(What:="*", After:=Range("A1"), SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
LastColumn = Cells.Find(What:="*", After:=Range("A1"), SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column
Range("A1").Resize(LastRow, LastColumn).Select
MsgBox "The data range address is " & Selection.Address(0, 0) & ".", 64, "Data-containing range address:"
End Sub
選擇未知起始位置的資料範圍
這個範例展示了當你不知道起始位置時,如何在目前工作表中選擇資料範圍,並向使用者顯示該範圍的地址。 資料範圍不包含格式化但不包含資料的儲存格。 為了取得資料範圍,此範例透過 Range 物件的 Find 方法,找出包含實際資料的第一列和最後一列。
Sub UnknownRange()
If WorksheetFunction.CountA(Cells) = 0 Then
MsgBox "There is no range to be selected.", , "No cells contain any values."
Exit Sub
Else
Dim FirstRow&, FirstCol&, LastRow&, LastCol&
Dim myUsedRange As Range
FirstRow = Cells.Find(What:="*", SearchDirection:=xlNext, SearchOrder:=xlByRows).Row
On Error Resume Next
FirstCol = Cells.Find(What:="*", SearchDirection:=xlNext, SearchOrder:=xlByColumns).Column
If Err.Number <> 0 Then
Err.Clear
MsgBox _
"There are horizontally merged cells on the sheet" & vbCrLf & _
"that should be removed in order to locate the range.", 64, "Please unmerge all cells."
Exit Sub
End If
LastRow = Cells.Find(What:="*", SearchDirection:=xlPrevious, SearchOrder:=xlByRows).Row
LastCol = Cells.Find(What:="*", SearchDirection:=xlPrevious, SearchOrder:=xlByColumns).Column
Set myUsedRange = Range(Cells(FirstRow, FirstCol), Cells(LastRow, LastCol))
myUsedRange.Select
MsgBox "The data range on this worksheet is " & myUsedRange.Address(0, 0) & ".", 64, "Range address:"
End If
End Sub
關於參與者
MVP Tom Urtis 是 Atlas Programming Management 的創辦人,這家公司位於矽谷,專門提供 Microsoft Office 和 Excel 商務解決方案全套服務。 Tom 擁有 25 年的業務管理和開發 Microsoft Office 應用程式的經驗,並共同編寫了《Holy Macro! It's 2,500 Excel VBA Examples》。
支援和意見反應
有關於 Office VBA 或這份文件的問題或意見反應嗎? 如需取得支援服務並提供意見反應的相關指導,請參閱 Office VBA 支援與意見反應。