如何在循环列中时比较同一行中两个不同列中的两个单元格?

时间:2016-12-23 18:43:14

标签: excel vba excel-vba loops

现在我的代码从L2开始循环到列中的最后一行。如果单元格值小于" Previous"然后使用ColorIndex为40突出显示该单元格。效果很好。

我真正想做的是能够同时循环第二列(它们在任何时候都会在同一行显然)。逻辑上它应该是这样的:

如果单元格值(从L2开始)小于" Previous"中的单元格的值。表单AND如果AE2的单元格值等于" #N / A" (注意:此时所有公式都已删除,因此"#N / A"是一个字符串)然后用ColorIndex为40突出显示L2单元格。任何帮助都表示赞赏。

Sub Comparing()

Sheets("Output").Select

Dim UsedRng As Range, LastRow As Long
Dim x As Long

Set UsedRng = ActiveSheet.UsedRange
LastRow = UsedRng(UsedRng.Cells.Count).Row

      Range("L2").Select

      Do Until ActiveCell.Row = LastRow + 1
        If ActiveCell.Value < Range("Previous!L2") Then
            ActiveCell.Interior.ColorIndex = 40
        End If

         ActiveCell.Offset(1, 0).Select
      Loop

End Sub

编辑:感谢您的回复。调整完成后,代码工作如下:

Sub Comparing()

Dim wsOut As Worksheet
Dim wsPrev As Worksheet
Dim r As Long
Dim LastRow As Long

Set wsOut = Worksheets("Output")
Set wsPrev = Worksheets("Previous")
LastRow = wsOut.UsedRange(wsOut.UsedRange.Cells.Count).Row

For r = 2 To LastRow
    If wsOut.Cells(r, "L").Value < wsPrev.Cells(2, "L").Value And _
        Application.WorksheetFunction.IsNA(wsOut.Cells(r, "AE").Value) Then
              wsOut.Cells(r, "L").EntireRow.Delete
    End If
Next

End Sub

2 个答案:

答案 0 :(得分:1)

重构代码后,更改变得简单(只需对If语句稍作更改):

Sub Comparing()
    Dim wsOut As Worksheet
    Dim wsPrev As Worksheet
    Dim r As Long
    Dim LastRow As Long
    Set wsOut = Worksheets("Output")
    Set wsPrev = Worksheets("Previous")
    LastRow = wsOut.UsedRange(wsOut.UsedRange.Cells.Count).Row
    For r = 2 To LastRow
        If wsOut.Cells(r, "L").Value < wsPrev.Cells(r, "L").Value And _
           wsOut.Cells(r, "AE").Value = "#N/A" Then
            wsOut.Cells(r, "L").Interior.ColorIndex = 40
        End If
    Next
End Sub

如果Previous!L2是专门针对第2行而不是正在处理的行,则r的引用应更改为该地点的2

此外,如果AE列中的单元格包含错误值#N/A而不是"#N/A"的字符串(您可以告诉我在Excel中尝试=LEN(AE2) - 如果它返回#N/A然后AE2包含错误值,但如果它返回4,那么AE2包含字符串值),您可以使用IsError来测试它。

Sub Comparing()
    Dim wsOut As Worksheet
    Dim wsPrev As Worksheet
    Dim r As Long
    Dim LastRow As Long
    Set wsOut = Worksheets("Output")
    Set wsPrev = Worksheets("Previous")
    LastRow = wsOut.UsedRange(wsOut.UsedRange.Cells.Count).Row
    For r = 2 To LastRow
        If wsOut.Cells(r, "L").Value < wsPrev.Cells(2, "L").Value And _
           IsError(wsOut.Cells(r, "AE")) Then
            wsOut.Cells(r, "L").Interior.ColorIndex = 40
        End If
    Next
End Sub

答案 1 :(得分:0)

如果我正确理解你的目标,你可能想尝试一下:

Option Explicit

Sub Comparing()
    Dim cell As Range
    Dim prevVal As Double

    prevVal = Worksheets("Previous").Range("L2")
    With Worksheets("Output1")
        For Each cell In .Range("AE2:AE" & .Cells(.Rows.count, "L").End(xlUp).row).SpecialCells(xlCellTypeConstants, xlErrors).Offset(, -19)
            If cell.Value < prevVal Then cell.Interior.ColorIndex = 40
        Next cell
    End With
End Sub