2017-02-16 64 views
0

代码找到标题行和正确的列。我想在同一列的标题行下开始一个单元格的范围内执行一些代码,直到同一列中的最后一行。我试图使用offset来创建范围,但每次都会失败offsetoffset不能用这种方式吗?Excel VBA:我在这个简单的OFFSET中错过了什么?

Sub Del_Y_Rows() 
Dim Rng, fcell, LastRow, SrchRng, sRNG, eRNG As Range 
Dim Findstring As String 
Findstring = "Header" 

With Sheets("thisSheet") 
    Set SrchRng = .Range("a1:l15") 
    Set fcell = SrchRng.Find(What:=Findstring, _ 
      LookAt:=xlWhole, _ 
      LookIn:=xlValues, _ 
      SearchOrder:=xlByRows, _ 
      MatchCase:=False) 
    LastRow = .Cells(Rows.Count, fcell.Column - 2).End(xlUp).Row 
    Debug.Print "fcell " & fcell.Address 

    sRNG = .Range(fcell).Offset(1, 0) 'this fails 'sRng = start of the range 
    Debug.Print "srng " & sRNG 
    eRng = .cells(LastRow, fcell.Column) 'eRng = end of the range 
    Rng = .Range(sRNG, eRng) 
    Debug.Print "rng is " & Rng.Address 
End With 
End Sub 
+0

测试'fcell是Nothing'。顺便说一句,只有'eRNG'是一个'范围'。其余部分隐含声明为“Variant” – Comintern

回答

0

fcell是一个范围,不需要RAnge()

sRNG = fcell.Offset(1, 0) 

还有一件事,你将要使用的支票,以确保FCELL实际上是一个范围,而不是什么都没有。

Sub Del_Y_Rows() 
Dim Rng As Range, fcell As Range, LastRow as Long , SrchRng As Range, sRNG As Range, eRNG As Range 
Dim Findstring As String 
Findstring = "Header" 

With Sheets("thisSheet") 
    Set SrchRng = .Range("a1:l15") 
    Set fcell = SrchRng.Find(What:=Findstring, _ 
      LookAt:=xlWhole, _ 
      LookIn:=xlValues, _ 
      SearchOrder:=xlByRows, _ 
      MatchCase:=False) 
    LastRow = .Cells(Rows.Count, fcell.Column - 2).End(xlUp).Row 
    If not fcell is nothing then 

     Debug.Print "fcell " & fcell.Address 

     set sRNG = fcell.Offset(1, 0) 'this fails 'sRng = start of the range 
     Debug.Print "srng " & sRNG 
     set eRng = .cells(LastRow, fcell.Column) 'eRng = end of the range 
     set Rng = .Range(sRNG, eRng) 
     Debug.Print "rng is " & Rng.Address 
    End If 
End With 
End Sub 
0

您必须使用Set for objects。

Set sRNG = .Range(fcell).Offset(1,0)