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

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

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

我想创build一个macros,它可以突出显示所有的正数和负数(例如1和-1),同时也考虑到可以出现多对的事实(例如3和3都出现两次)。 另外,我希望能够input我想要使用的范围。

对于上面的例子,除了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条件在那里。 我尝试了“下一个单元格”和“下一个迭代”,但什么也没有。 我没有得到什么?

代替:

If cell.Interior.ColorIndex = 30 Then Next

您需要testing相反的结果,并允许它运行代码,如果是true:

 If cell.Interior.ColorIndex <> 30 Then 

你也使用.Value在许多地方,不允许它:

Set CValue = Cell.Value

应该:

 Set CValue = Cell 

但真的不需要,因为Cell已经是一个范围。

不要忘记声明你的variables:

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

同样在查找中,我们希望从当前单元格search下来,所以更改:

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 

在这里输入图像描述