将选择范围扩展到最后使用的列vba

时间:2018-07-04 09:01:31

标签: excel vba excel-vba

代码:

Sub MyColumnSelect()
Dim myCurrentRow As Long
Dim myLastColumn As Long
myCurrentRow = ActiveCell.Row
myLastColumn = ActiveCell.SpecialCells(xlLastCell).Column
Range(ActiveCell, Cells(myCurrentRow, myLastColumn)).Select
End Sub


我需要将选择范围从任何列或任何行扩展到工作表中最后使用的列。此代码将选择范围扩展到特定列,在我的情况下扩展到column P。我不知道为什么会这样,但是即使只有4列,它仍然会将选择范围扩展到column P

图片:
enter image description here

PS:我知道我不应该使用select,但是即使使用select,我也无法使用它。需要帮忙。

3 个答案:

答案 0 :(得分:1)

完全使用Google搜寻绝对可以找到答案。这是检索最后一个活跃使用的行的最常见方法

Shets("Sheetname").Cells(Rows.Count, <inColumn>).End(xlUp).Row

和列

Shets("Sheetname").Cells(<inRow>, Columns.Count).End(xlToLeft).Column

在您的情况下,假设您的工作表名为“ Sheet1”,则为:

Dim lr as Long
Dim lc as Long
lr = Sheets("Sheet1").Cells(Rows.Count, 2).End(xlUp).Row
lc = Sheets("Sheet1").Cells(4, Columns.Count).End(xlToLeft).Column

很显然,如果您的列范围有所不同,则应以循环方式检索它们(例如,循环遍历所有活动行)

For i = 3 to lr
   lc = Sheets("Sheet1").Cells(i, Columns.Count).End(xlToLeft).Column
   ' do something
Next i

Also, do absolutely read up on why you should not use Select, ActiveSheet and so on..

答案 1 :(得分:1)

尝试一下:

Sub MyColumnSelect()

Dim myRow, myLastColumn As Long

 For myRow = 3 To ActiveSheet.Cells(Rows.Count, 2).End(xlUp).Row

  myLastColumn = ActiveSheet.Cells(myRow, Columns.Count).End(xlToLeft).Column

  ActiveSheet.Range(Cells(myRow, 1), Cells(myRow, myLastColumn)).Copy

 Next

End Sub

答案 2 :(得分:1)

Ron de Bruin - Find last row, column or last cell向您展示如何查找最后使用的列。

Sub MyColumnSelect()
    Dim myCurrentRow As Long
    Dim myLastColumn As Long
    myCurrentRow = ActiveCell.Row
    myLastColumn = Cells.Find(What:="*", After:=Cells(1, 1), _
                        Lookat:=xlPart, LookIn:=xlFormulas, SearchOrder:=xlByColumns, _
                        SearchDirection:=xlPrevious, MatchCase:=False).Column

    Range(ActiveCell, Cells(myCurrentRow, myLastColumn)).Select
End Sub

这也可以。但是请注意,UsedRange有时可能会超出数据范围而扩展到非连续格式。

  Intersect(ActiveCell.EntireRow, ActiveSheet.UsedRange).Select

附录

@Rawrplus指出,使用ActiveCellSelection是坏习惯,应避免使用。观看:Excel VBA Introduction Part 5 - Selecting Cells (Range, Cells, Activecell, End, Offset)