比较一个循环中的单元格与VBA

我被要求在VBA中编写一个快速macros,用于比较Excel电子表格中两个不同单元格的值,然后如果值小于另一个,则将其中一个单元格更改为红色。 我能够为一组单元做到这一点,但还没有想出如何为多个单元做到这一点。 在我的macros,我比较“E37”与“C40”。 我需要对“E44”和“C47”等进行相同的比较,每次我为每个值向下移动7行。 如果单元格为空,我还需要一个命令来停止例程,因为并不是所有的电子表格都是相同的长度。

每当数值input电子表格时,我已经得到了一个执行这个macros的macros。 我在表单级别分配它,只需要find一种方法来比较单元格。 请参阅下面的代码。

Sub colorcellMacro() ' ' colorcellMacro Macro ' change background color according to ref length ' Range("E37").Select If Range("E37") < Range("C40") Then Range("E37").Select With Selection.Interior .Pattern = xlSolid .PatternColorIndex = xlAutomatic .Color = 255 .TintAndShade = 0 .PatternTintAndShade = 0 Range("H24").Select End With Else Range("E37").Select With Selection.Interior .Pattern = xlNone .TintAndShade = 0 .PatternTintAndShade = 0 End With End If End Sub 

这是我最终使用的,这是两个build议的组合。

 'Sub colorcellMacro() ' ' colorcellMacro Macro ' change background color according to ref length ' ' Dim firstIndex, secIndex As Integer firstIndex = 37 secIndex = 40 Do While Range("E" & firstIndex).Value <> "" And Range("C" & secIndex).Value <> "" If Range("E" & firstIndex).Value < Range("C" & secIndex).Value Then Range("E" & firstIndex).Select With Selection.Interior .Pattern = xlSolid .PatternColorIndex = xlAutomatic .Color = 255 .TintAndShade = 0 .PatternTintAndShade = 0 Range("H24").Select End With Else Range("E" & firstIndex).Select With Selection.Interior .Pattern = xlNone .TintAndShade = 0 .PatternTintAndShade = 0 End With End If firstIndex = firstIndex + 7 secIndex = secIndex + 7 Loop End Sub 

 Dim firstIndex, secIndex as Integer firstIndex = 37 secIndex = 40 while Range("E" & firstIndex).Value <> "" and Range("C" & secIndex).value <> "" Then ` Do the comparison here ` Change the color here firstIndex = firstIndex + 7 secIndex = secIndex + 7 next 

尝试这个。 如果这不起作用,将会是这样或接近它。

这应该工作。 我包括你通知的着色代码:

 Sub colorCellMacro() Dim firstRow As Integer Dim secondRow As Integer firstRow = 37 secondRow = 40 Do While Cells(firstRow, 5) <> "" And Cells(secondRow, 3) <> "" If Cells(firstRow, 5).Value < Cells(secondRow, 3).Value Then Cells(firstRow, 5).Select With Selection.Interior .Pattern = xlSolid .PatternColorIndex = xlAutomatic .Color = 255 .TintAndShade = 0 .PatternTintAndShade = 0 Range("H24").Select End With Else Cells(firstRow, 5).Select With Selection.Interior .Pattern = xlNone .TintAndShade = 0 .PatternTintAndShade = 0 End With End If firstRow = firstRow + 7 secondRow = secondRow + 7 Loop End Sub