2016-03-04 279 views
1

我有以下代碼,但在Set CellRange = wks.Range(srange).Select行上收到「Object Required」錯誤。Excel VBA選擇單元格範圍

我已經嘗試了很多東西,但無法弄清楚。我想根據特定單元格值在選定範圍上設置背景顏色。

Function RowColor() 
    Application.Volatile 
    Dim wks As Worksheet 
    Set wks = ActiveSheet 
    Dim x As Integer 
    Dim FirstRow As Integer 
    Dim CellRange As Range 
    Dim LastRow As Long 

    LastRow = wks.Cells(wks.Rows.Count, "A").End(xlUp).Row 
    FirstRow = 6 

    'Loop through each row 
    ScreenUpdating = False 

    For x = FirstRow To LastRow 
    Let srange = "A" & x & ":" & "Z" & x 
    Set CellRange = wks.Range(srange).Select 


    Select Case wks.Cells(x, "R").Value 

     Case "O" 
      CellRange.Interior.Color = RGB(255, 192, 0) 

     Case "D" 
      CellRange.Interior.Color = RGB(255, 255, 0) 
     Case "C" 
     If wks.Cells(x, "Y") >= 0 Then 
      CellRange.Interior.Color = RGB(146, 208, 80) 
     Else 
      CellRange.Interior.Color = RGB(255, 0, 0) 
     End If 
     Case "W" 
      CellRange.Interior.Color = RGB(0, 176, 240) 
    End Select 
    Next x 
    ScreenUpdating = True 

End Function 
+5

最後刪除'.Select'。 –

+0

@WaiHaLee如果OP想要一個實際的答案,我會的。他們投下的票不是爲了「偷」我的答案,而是因爲他們的評論不是答案。如果他們把他們的意見歸類並刪除他們的答案,他們會得到他們的代表點。 –

回答

-3

Scott在註釋中是正確的:在結尾處刪除.Select。

選擇單元格不會返回任何內容。

2

按我的意見,這已經得到了太多的讚譽,改變這種:

Set CellRange = wks.Range(srange).Select 

要:

Set CellRange = wks.Range(srange) 

取出.Select。其中一個不使用.Select功能設置範圍對象。只需將範圍對象設置爲範圍即可。