VBA帮助您选择最后一行并选择范围

时间:2016-03-21 20:49:15

标签: excel vba

以下代码执行以下操作:

  1. 从A1开始,它搜索最后一个填充的单元格并选择 紧随其后的牢房。
  2. 选择第一个可用空白单元格后,选择整行
  3. 然后整个行用颜色索引16着色。
  4. 你走了:

    Sub Macro1()
    
    Range("A1").End(xlDown).Offset(1, 0).Select
    Range(Selection, Selection.End(xlToRight)).Select
    With Selection.Interior
        .ColorIndex = 16
        End With
    End Sub
    

    这很好用,但我很难在该行中只选择A到H列。我不想选择整行。

    有人可以帮帮我吗?我一直在收到End With错误而不确定如何解决它:S

    非常感谢你的时间和考虑!

3 个答案:

答案 0 :(得分:2)

您可以为您的选择设置范围,这里是另一种从列末尾(版本1)查找最后一行的方法 - (Rows.Count,1)表示A列(Rows.Count,2)将代表B栏等......

这是第一版:从A栏末尾开始寻找空行:

  Dim rowNum As Integer
    rowNum = Cells(Rows.Count, 1).End(xlUp).Row + 1
    Dim rng As Range
    Set rng = Range(Cells(rowNum, 1), Cells(rowNum, 8))
    rng.Interior.ColorIndex = 16

这是版本2:从A列的开头(第1行)开始寻找空行:

Dim rowNum As Integer
rowNum = Range("A1").End(xlDown).Offset(1, 0).Row
Dim rng As Range
Set rng = Range(Cells(rowNum, 1), Cells(rowNum, 8))
rng.Interior.ColorIndex = 16

答案 1 :(得分:1)

选择太多了! <怎么样

Sub Macro1()
currentRow = Range("A1").end(xldown).offset(1,0).row
Range(cells(currentRow, 1), cells(currentRow,8)).Interior.ColorIndex = 16
cells(currentRow,1)= " "
End Sub

这有用吗?

答案 2 :(得分:1)

试试这个:

'Declare Variables
Dim rowNum as integer
Dim YourRange as range

'Find last row by counting cells not empty and adding 1
'Assumes that all cells from A1 down are filled. Change the +1 accordingly if not
rowNum = worksheetfunction.counta(activesheet.columns(1))+1

'Set range object to column A through H of your row number
Set YourRange = Activesheet.Range("A" & rowNum & ":H" & rowNum)

'Set interior color of the rnage object instead of using Selection
YourRange.interior.colorindex=16