2016-11-23 35 views
0

我試圖循環遍歷可變數目的行,在列E(即「WLO」)中搜索值。當我在列E中找到一行具有「WLO」的行時,我想從列J中選擇該行中的單元格,直到該行中的數據結束。列J後填充的列數將有所不同,因爲這在多個電子表格中使用,所以右側的選擇需要是動態的。我想要執行類似下面的代碼,但是目前它會將第一個WLO實例與最後一個WLO紅色實例之間的每一行都變成一個行,即使其間存在其他值的行。 See Screenshot of current results here.循環遍歷行並選擇要編輯的列的動態範圍

Sub Color_row() 
    Dim EndRow As Long 
    Dim e As Long 

    EndRow = Range("E" & Rows.Count).End(xlUp).Row 

    For e = 2 To EndRow 
    If (Range("E" & e).Value = "WLO") Then 
     Range("J" & e, Selection.End(xlToRight)).Interior.ColorIndex = 3 
    End If 
    Next e 

End Sub 

This is an example of I would like to be able to do 感謝您的任何意見。非常感謝!

回答

0

您需要先創建一個結束範圍。你近了!

Sub Color_row() 
    Dim EndRow As Long 
    Dim e As Long 
    Dim EndCol, StartCol As Range 

    EndRow = Range("E" & Rows.Count).End(xlUp).Row 

    For e = 2 To EndRow 
    If (Range("E" & e).Value = "WLO") Then 
     Set EndCol = Range("J" & e).End(xlToRight) 
     Set StartCol = Range("J" & e) 
     Range(StartCol, EndCol).Interior.ColorIndex = 3 
    End If 
    Next e 

End Sub 
+0

這工作完美!非常感謝你!! – lsmith

0

在你的Then子句中,Selection是活動單元格所在的位置,所以它會突出顯示該行。將選區更改爲您的起點,即J和行號。

Sub Color_row() 
    Dim EndRow As Long 
    Dim e As Long 

    EndRow = Range("E" & Rows.Count).End(xlUp).Row 

    For e = 2 To EndRow 
    If (Range("E" & e).Value = "WLO") Then 
     Range("J" & e, Range("J" & e).End(xlToRight)).Interior.ColorIndex = 3 
    End If 
    Next e 

End Sub 
+0

這很有道理!謝謝! – lsmith