将偏移量(1,0),偏移量(-1,0)和目标单元格合并为一个循环中的代码

时间:2014-07-17 03:29:21

标签: vba excel-vba excel

知道如何将以下3个块合并为1个吗?我有很多工作表,它变得疯狂...感谢社区! :)

Dim i As Long 
Dim j As Long

For i = 3 To 73 Step 3
For j = 2 To 33

Set curcell = Worksheets("Earliest Corr").Cells(i, j)

  If curcell.Value < 0.05 Then
    curcell.Interior.ColorIndex = 45
  ElseIf curcell.Value >= 0.05 And curcell.Value < 0.1 Then
    curcell.Interior.ColorIndex = 6
  ElseIf curcell.Value >= 0.1 And curcell.Value < 0.2 Then
    curcell.Interior.ColorIndex = 36
End If

  If curcell.Value < 0.05 Then
    curcell.Offset(1, 0).Interior.ColorIndex = 45
  ElseIf curcell.Value >= 0.05 And curcell.Value < 0.1 Then
    curcell.Offset(1, 0).Interior.ColorIndex = 6
  ElseIf curcell.Value >= 0.1 And curcell.Value < 0.2 Then
    curcell.Offset(1, 0).Interior.ColorIndex = 36
End If

  If curcell.Value < 0.05 Then
    curcell.Offset(-1, 0).Interior.ColorIndex = 45
  ElseIf curcell.Value >= 0.05 And curcell.Value < 0.1 Then
    curcell.Offset(-1, 0).Interior.ColorIndex = 6
  ElseIf curcell.Value >= 0.1 And curcell.Value < 0.2 Then
    curcell.Offset(-1, 0).Interior.ColorIndex = 36
End If

1 个答案:

答案 0 :(得分:0)

您可以通过将三个目标单元格合并到一个范围对象中来压缩这些代码块。同样在您的ElseIf区块中,您不需要第一个条件。为了达到你的第一个ElseIf,我们已经知道currcell的值大于或等于0.5。

Dim rng As Range, curcell As Range
Dim i As Long, j As Long

For i = 3 To 73 Step 3
    For j = 2 To 33
        Set curcell = Worksheets("Earliest Corr").Cells(i, j)
        Set rng = Worksheets("Earliest Corr").Range(Cells(i - 1, j), Cells(i + 1, j))
        If curcell.Value < 0.05 Then
            rng.Interior.ColorIndex = 45
        ElseIf curcell.Value < 0.1 Then
            rng.Interior.ColorIndex = 6
        ElseIf curcell.Value < 0.2 Then
            rng.Interior.ColorIndex = 36
        End If
    Next j
Next i
相关问题