2013-10-18 52 views
-1

如何修改以下內容以將選擇限制爲僅在第2行開始?目前它選擇每一行。如何在第2行開始選擇,而不是所有行?

Set myRng = .Range("D2", .Cells(.Rows.Count, "D").End(xlUp)) 
+0

如果D列中沒有任何內容或者選擇了D2:D(last_row_with_data_in_D),則顯示的代碼選擇行1:2,不是嗎?除了直到D列最後一行有數據之外,我不覺得可以選擇所有行。 –

回答

1

要使其工作,您將必須確保單元格D2中有數據。看到這個例子。

Sub Sample() 
    Dim myRng As Range 
    Dim ws As Worksheet 
    Dim Lrow As Long 

    '~~> Change this to the relevant worksheet 
    Set ws = ThisWorkbook.Sheets("Sheet1") 

    With ws 
     '~~> Get last row which has data in Col D 
     Lrow = .Range("D" & .Rows.Count).End(xlUp).row 

     If Not Lrow < 2 Then 
      Set myRng = .Range("D2:D" & Lrow) 
      MsgBox myRng.Address 
     Else 
      MsgBox "There is no data in cell D2" 
     End If 
    End With 
End Sub 
相關問題