将范围设置为最后一行

你好我正在设置范围到最后一行。

我有

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 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 

谢谢

尝试下面的代码:你也可以参考这个链接的细节。

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

要么

  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 

要么

 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 

为了这个问题,这个问题已经完成了,但我使用了一些不同的东西:

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