2013-05-03 77 views
1

您好,我正在嘗試將範圍設置爲最後一行。將範圍設置爲最後一行

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 

謝謝

+0

你到底去做 ?遍歷大範圍內的每個單元幾乎總是一個壞主意和糟糕的設計。 – ApplePie 2013-05-03 14:48:52

+0

[Last Range in Range]的可能重複(http://stackoverflow.com/questions/12588424/last-row-in-range) – whytheq 2013-05-03 20:51:37

回答

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

我建議不要使用第一個選項。如果電子表格中有部分(內容中的分隔),則無法計算正確的範圍。我會用第二個。 – ApplePie 2013-05-03 14:51:05

+0

這是偉大的,如果CG不是最後一列,第二個選項是否工作?再次感謝Santosh – xyz 2013-05-03 15:49:49

1

對於它的價值這個問題已經做了死,但我用不同的東西:

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