2017-01-13 99 views
1

我有一個工作表,有多列和多行數據。數據的相關部分在列a中存在具有一些文本(例如,ident)的單元格時開始。陳述單元格位置的變量

我嘗試使用,如果要經過細胞,直到找到「標識」的單元格,返回其行號(和可變分配到該行號)

代碼我使用:

For Each Cell In ActiveSheet.Range("A") 
      If ActiveSheet.Cells.Value = "Ident" Then 
       start1 = ActiveCell.Row 
       Exit For 
      End If 
     Next Row 

問題是,單元術語給我一個錯誤(我可能引用它錯誤)。在這種情況下,在「for each」之後需要使用什麼來遍歷A列中的單元格?

回答

2
For Each cell In ActiveSheet.Range("A:A") 
    If cell.Value = "Ident" Then 
     start1 = cell.Row 
     Exit For 
    End If 
Next 

您還可以考慮的改進這兩個進一步的步驟(從圖的邏輯和速度點):

  • 步驟1

    循環只有通過與某個常數文本值單元在它

    For Each cell In ActiveSheet.Range("A:A").SpecialCells(xlCellTypeConstants, xlTextValues) 
        If cell.Value = "Ident" Then 
         start1 = cell.Row 
         Exit For 
        End If 
    Next 
    
  • 步驟2

    使用Find()方法,避免循環

    Set cell = ActiveSheet.Range("A:A").SpecialCells(xlCellTypeConstants, xlTextValues).Find(what:="ident", lookat:=xlWhole, LookIn:=xlValues, MatchCase:=True) 
    If Not cell Is Nothing Then start1 = cell.Row 
    

    ,你必須同時始終指定值LookInLookAtMatchValue參數和仔細選擇他們

+1

錯誤是:1)'範圍( 「A」)' - >'範圍( 「A:A」)'2)'ActiveSheet.Cells.Value' - >'cell.Value' 3)'ActiveCell.Row' - >'cell.Row' 4)'Next Row' - >'Next cell'(或簡單的'Next') – user3598756

0

另一種選擇,通過列循環。

Option Explicit 

Public Sub TestMe() 

    Dim cell As Range 

    For Each cell In ActiveSheet.Columns(1).Cells 
     If cell.Value = "Ident" Then 
      Debug.Print cell.Row 
      Exit For 
     End If 
    Next cell 

End Sub 
在你的代碼