2017-02-16 54 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)

相關問題