将范围设置为最后一行

时间:2013-05-03 14:23:57

标签: excel excel-vba vba

您好我正在尝试将范围设置为最后一行。

我有

For Each rng In Sheets("Sheet1").Range("B2:CG100").Cells 'adjust sheetname and range accordingly

我试过

For Each rng In Sheets("Sheet1").Range("B2:CG" & lastRow).Cells 'adjust sheetname and range accordingly

但没有工作

问题是最后一行会发生变化,如果我使用整个列,则Sub会永远运行

Sub CleanAll()
    Dim rng As Range

    For Each rng In Sheets("Sheet1").Range("B2:CG100").Cells 'adjust sheetname and range accordingly
        rng.Value = NumberOnly(rng.Value)
    Next
End Sub

由于

2 个答案:

答案 0 :(得分:1)

尝试以下代码:您也可以参考此link了解详细信息。

Sub CleanAll()

        Dim rng As Range

        For Each rng In Sheets("Sheet1").Range("B2").CurrentRegion
            rng.Value = NumberOnly(rng.Value)
        Next
 End Sub

OR

 Sub CleanAll()

        Dim rng As Range
        Dim lastRow As Long
        Dim lastCol As Long
        Dim colChr As String


        With Sheets("sheet1")
            lastCol = .Cells(2, .Columns.Count).End(xlToLeft).Column
            lastRow = .Cells(.Rows.Count, lastCol).End(xlUp).Row
        End With


        For Each rng In Sheets("Sheet1").Range(Cells(2, 2), Cells(lastRow, lastCol))
           rng.Value = NumberOnly(rng.Value)
        Next
End Sub

OR

Sub CleanAll()

        Dim rng As Range
        Dim lastRow As Long

        With Sheets("sheet1")
            lastRow = .Range("CG" & .Rows.Count).End(xlUp).Row
        End With

        For Each rng In Sheets("Sheet1").Range("B2:CG" & lastRow)
            rng.Value = NumberOnly(rng.Value)
        Next
    End Sub

答案 1 :(得分:1)

对于什么是值得这个问题已经完成了死亡,但我使用了不同的东西:

With ActiveSheet.Cells
    last_column = .Find("*", SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column
    last_row = .Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
End With
相关问题