2017-01-13 85 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 
在你的代码