Excel VBA - 突出显示正数和负数对

时间:2017-11-13 14:28:05

标签: excel vba excel-vba

假设我有一列数字,例如:

  

1; -1; 5; 4; 3; -3; -3; 3; -4; 7。

我想制作一个可以突出显示所有正负数对(例如1和-1)的宏,同时还考虑到可以出现多对的事实(例如3和-3都出现两次) 。此外,我希望能够输入我想要使用的范围。

对于上面的示例,除了5和7之外,所有数字都应突出显示。

这是我到目前为止所提出的

Sub HighlightExercise()

Set myRange = Application.InputBox(prompt:="Sample", Type:=8)

myRange.Interior.ColorIndex = 2

For Each cell In myRange

If cell.Interior.ColorIndex = 30 Then Next

Set CValue = Cell.Value

myRange.Select

Set CFind = Selection.Find(What:=CValue.Value * -1, After:=ActiveCell, LookIn:= _
    xlFormulas, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:= _
    xlNext, MatchCase:=False, SearchFormat:=False)

If CFind.Value = Null Then Next

If CFind.Interior.ColorIndex = 30 Then Next

CFind.Interior.ColorIndex = 30

CValue.Interior.ColorIndex = 30

Next

End Sub

在上面的例子中,它表示“编译错误,下一个没有For”但For条件就在那里。我试过“Next Cell”和“Next iteration”但仍然没有。我没得到什么?

1 个答案:

答案 0 :(得分:6)

而不是:

  

If cell.Interior.ColorIndex = 30 Then Next

如果为true,您需要测试相反的情况并允许它运行代码:

If cell.Interior.ColorIndex <> 30 Then

您也可以在许多不允许的地方使用.Value

  

Set CValue = Cell.Value

应该是:

Set CValue = Cell

但实际上并不需要,因为Cell已经是一个范围。

不要忘记申报变量:

Dim myRange As Range
Dim cell As Range
Dim cfind As Range

同样在Find中,我们希望从当前单元格中进行搜索以进行更改:

  

After:=ActiveCell

After:=cell

避免使用.Select只需按照范围执行操作:

Set cfind = myRange.Find...

尝试:

Sub HighlightExercise()
Dim myRange As Range
Dim cell As Range
Dim cfind As Range
Set myRange = Application.InputBox(prompt:="Sample", Type:=8)

myRange.Interior.ColorIndex = 2

For Each cell In myRange

    If cell.Interior.ColorIndex <> 30 Then

        Set cfind = myRange.Find(What:=cell.Value * -1, After:=cell, LookIn:= _
            xlFormulas, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:= _
            xlNext, MatchCase:=False, SearchFormat:=False)
        If Not cfind Is Nothing Then
            If cfind.Interior.ColorIndex <> 30 Then
                cfind.Interior.ColorIndex = 30
                cell.Interior.ColorIndex = 30
            End If
        End If
    End If
Next

enter image description here