尝试将列a中的单元格与列b vba中的单元格进行比较

时间:2017-04-21 13:05:10

标签: excel vba excel-vba

我对VBA很新,并且在找到我需要的答案方面非常成功,直到现在。我想在A列中取一个值,看看它是否出现在B列中并在找到该值时执行一个动作,然后转到B列中的下一列。我觉得我很接近只是没有得到正确的结果。

这是我到目前为止所尝试的内容

x = [1,1,3,4,0,0,0,5,1]
zip(x, range(0, len(x)))
[(1, 0), (1, 1), (3, 2), (4, 3), (0, 4), (0, 5), (0, 6), (5, 7), (1, 8)]
[c for c in new_x if c[0]!=0]
[(1, 0), (1, 1), (3, 2), (4, 3), (5, 7), (1, 8)]

2 个答案:

答案 0 :(得分:1)

Sub CompareCells()
Dim CellInColA As Range
Dim CellInColB As Range
  For Each CellInColA In Application.Intersect(ActiveSheet.UsedRange, Columns("A").Cells)
    For Each CellInColB In Application.Intersect(ActiveSheet.UsedRange, Columns("B").Cells)
      If CellInColB = CellInColA Then
        'found it - do whatever
        CellInColB.Interior.ColorIndex = 3
        Exit For
      End If
    Next CellInColB
  Next CellInColA
End Sub

答案 1 :(得分:0)

以下是您的问题的可能解决方案,尽可能使用您的代码:

Option Explicit

Sub TestMe()

    Dim currentA    As String
    Dim currentB    As String

    Dim a           As Long
    Dim b           As Long

    Dim cellA       As Range
    Dim cellB       As Range

    a = 2
    b = 1

    With ActiveSheet
        Set cellA = .Range("A2")

        Do Until IsEmpty(cellA)
            Set cellA = .Cells(a, b)
            a = a + 1

            Set cellB = .Range("B2")

            Do Until IsEmpty(cellB)
                If cellA.Value = cellB.Value Then
                    PaintMe cellA
                    PaintMe cellB
                End If

                Set cellB = cellB.Offset(1, 0)
            Loop
        Loop

    End With
End Sub

Public Sub PaintMe(cellA As Range)

    With cellA.Interior
        .Pattern = xlSolid
        .PatternColorIndex = xlAutomatic
        .ThemeColor = xlThemeColorAccent1
        .Color = 65535
        .PatternTintAndShade = 0
        .TintAndShade = 0
    End With

End Sub

我做了什么:

  1. 单元格和范围用点表示在Activesheet中。
  2. 我更新了循环,所以它们看起来更好。
  3. 我制作了一个特殊的子PaintMe,用于绘制左侧和右侧列。
  4. 我避免使用ActiveCell,因为它很慢而且很难 - 请在此处查看更多内容 - How to avoid using Select in Excel VBA macros
  5. 这是输出的样本:

    enter image description here

    一般来说,像这样的解决方案非常专业,因为它有一个algorithm complexity of n²,这可能是这种问题的最坏情况。你有2个循环,这是最慢的解决方案。总的来说,有更好的方法可以做到这一点。但是对于excel,它应该有用。