Excel VBA,比较多个列值,颜色单元格

时间:2013-11-16 14:55:43

标签: excel vba excel-vba

我是Excel中的VBA新手,我遇到了一些麻烦。我有3列A,C和F.如果它们与2个条件中的任何一个匹配,我只想突出显示那些列中的单元格。突出显示A列中具有重复值的任何单元格,然后仅在列C和F中突出显示单元格,如果列C的值为99.99或更高,列F在单元格中除了“测试”之外没有任何内容。

Sub Highlight()
Dim index As Integer
For index = 1 To 4
'Checks if any cells in Column C has value greater than 99.99 when Column F isn't "Test" or checks if multiple values exist in Column A (which I don't know)
If Range("C1") And Cell.Value > "99.99" And Range("F1") And Cell.Text <> "Current"  Then
'Highlighs both cell values Yellow (this is where I run into trouble)
Cell.Interior.ColorIndex = vbYellow
End If
Next index
End Sub

1 个答案:

答案 0 :(得分:0)

你只是指你的范围错了。 Cell未设置。我看不到你在哪里指的是A列。

此外,如果您使用的是内置颜色常量,则应使用.Color而非ColorIndex。

Sub Highlight()
Dim index As Integer
Dim ws As Worksheet

'set the sheet to use
Set ws = Sheet1

    For index = 1 To 4

    'Checks if any cells in Column C has value greater than 99.99 when Column F isn't "Test" or checks if multiple values exist in Column A (which I don't know)
        If ws.Range("C" & index).Value > "99.99" And ws.Range("F" & index).Text <> "Current" Then
        'Highlighs both cell values Yellow (this is where I run into trouble)
        ws.Range("C" & index).Interior.Color = vbYellow
        ws.Range("F" & index).Interior.Color = vbYellow
        End If

    Next index

End Sub

旁注。您可能最好使用条件格式来实现您想要的而不是VBA。

互联网上有很多关于这方面的教程:

http://chandoo.org/wp/2009/03/13/excel-conditional-formatting-basics/

http://spreadsheets.about.com/od/advancedexcel/tp/090822-excel-conditional-formatting-hub.htm