[英]Selecting a range until the last used row
我正在嘗試 select 一個范圍,直到工作表中最后使用的行。 我目前有以下內容:
Sub Select_Active_Down()
Dim lr As Long
lr = ActiveSheet.UsedRange.Rows.Count
If Cells(ActiveCell.Row, ActiveCell.Column) = Cells(lr, ActiveCell.Column) Then
MsgBox "There isn't any data to select."
Else
Range(Cells(ActiveCell.Row, ActiveCell.Column), Cells(lr, ActiveCell.Column)).Select
Cells(lr, ActiveCell.Column).Activate
End If
End Sub
問題是我需要 select 多列,這只會 select 活動范圍的第一列。 如何將其修改為 select 多列而不是第一列?
選擇整個區域呢? 這可以在 VBA 中按如下方式完成:
Selection.CurrentRegion.Select
還有可能是 select 整個陣列。 為此,只需按Ctrl+G ,選擇Special
並在那里查看。
我會這樣做略有不同。 我會使用.Find
來查找最后一行和最后一列(使用鏈接中顯示的相同邏輯)來構建我的范圍,而不是使用Selection | Select | ActiveCell | UsedRange | ActiveSheet
Selection | Select | ActiveCell | UsedRange | ActiveSheet
Selection | Select | ActiveCell | UsedRange | ActiveSheet
。
這是你正在嘗試的嗎?
Option Explicit
Sub Sample()
Dim ws As Worksheet
Dim LastRow As Long
Dim LastColumn As Long
Dim rng As Range
'~~> Change it to the relevant sheet
Set ws = Sheet1
With ws
'~~> Check if there is data
If Application.WorksheetFunction.CountA(.Cells) = 0 Then
MsgBox "No Data Found"
Exit Sub
End If
'~~> Find last row
LastRow = .Cells.Find(What:="*", _
After:=.Range("A1"), _
Lookat:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row
'~~> Find last column
LastColumn = .Cells.Find(What:="*", _
After:=.Range("A1"), _
Lookat:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByColumns, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Column
'~~> Construct your range
Set rng = .Range(.Cells(1, 1), .Cells(LastRow, LastColumn))
'~~> Work with the range
With rng
MsgBox .Address
'
'~~> Do what you want with the range here
'
End With
End With
End Sub
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.