2012-10-25 175 views
0

我試圖在可以解決以下問題的excel宏中查找代碼。在條件下着色Excel單元格

如果第一列包含任何文本,則使用某種顏色突出顯示第一列單元格,直到下一個文本不出現在同一列中。當任何文本出現在同一列中時,開始用不同顏色對單元格着色。

我必須對我的工作簿中的所有工作表重複此操作。 謝謝。

enter image description here

現在,我使用這個宏顏色,這是空 的細胞,但問題是,每當一個文本遇到

Sub try() 
Dim i As Integer 
Dim j As Integer 
Dim k As Integer 
i = 200 
j = 100 
k = 5 

Application.ScreenUpdating = False 

With ActiveSheet.UsedRange 
    .AutoFilter Field:=1, Criteria1:="" 
    If WorksheetFunction.CountBlank(.Columns(1)) > 0 Then 
     .Columns(1).SpecialCells(xlCellTypeBlanks).Interior.Color = RGB(i, j, k) 
    Else 
     i = i - 50 
     j = j - 10 
     k = 255 
    End If 

    .AutoFilter 
End With 

Application.ScreenUpdating = True 

End Sub 
+0

給單元格的背景顏色着色,試試cells.interior.color = RGB(255,0,0)'紅色 – Larry

+0

請更清楚地解釋一下你正在努力實現。你給的例子只顯示了黃色的A,綠色的B和藍色的C.這是什麼意思?嘗試一些,然後回到我們的任何具體問題。投票結束。 –

+0

正如我以前告訴我必須爲行着色,直到遇到文本,然後更改顏色 – Cprog

回答

1

這裏的顏色不列入變化你去:

Option Explicit 

Sub Color_Ranges() 

Dim oSheet     As Worksheet 
Dim oRange     As Range 
Dim oRange_Color   As Range 
Dim oBaseCell    As Range 
Dim lLast_Row    As Long 
Dim lRange_Rows    As Long 
Dim iCnt_Values    As Integer 
Dim iCnt_Intervals   As Integer 

Dim r      As Integer 
Dim g      As Integer 
Dim b      As Integer 

Dim iCnt     As Integer 


Set oSheet = ThisWorkbook.Sheets(1) 
With oSheet 
    lLast_Row = .Range("A1").SpecialCells(xlCellTypeLastCell).Row 
End With 

'Total range you want to color 
Set oRange = oSheet.Range(Cells(1, 1), Cells(lLast_Row, 1)) 
lRange_Rows = oRange.Rows.Count 

'Count values 
iCnt_Values = WorksheetFunction.CountA(oRange) 
'Count intervals 
iCnt_Intervals = iCnt_Values - 1 

'Generate random colors 
r = CInt(Int((255 * Rnd()) + 1)) 
g = CInt(Int((255 * Rnd()) + 1)) 
b = CInt(Int((255 * Rnd()) + 1)) 

Set oBaseCell = oRange.Cells(1, 1) 
For iCnt = 1 To iCnt_Intervals 
    Set oRange_Color = Range(oBaseCell, oBaseCell.End(xlDown)) 
    oRange_Color.Interior.Color = RGB(r, g, b) 
    r = CInt(Int((255 * Rnd()) + 1)) 
    g = CInt(Int((255 * Rnd()) + 1)) 
    b = CInt(Int((255 * Rnd()) + 1)) 
    Set oBaseCell = oBaseCell.End(xlDown) 
    Set oRange_Color = Nothing 
Next iCnt 

End Sub