尝试比较列a中的细胞和列b vba中的细胞
我对VBA相当陌生,直到现在,在find我需要的答案方面相当成功。 我想在列A中取一个值,看它是否出现在列B中,并在find该值时执行一个操作,然后转到列B中的下一列。我觉得我近了,只是没有得到正确的东西。
这是我迄今为止所尝试的
Sub Macro1() ' ' Macro1 Macro Dim currentA As String Dim currentB As String Dim a As Integer Dim b As Integer a = 2 b = 1 Do Until IsEmpty(ActiveCell) Cells(a, b).Select currentA = ActiveCell Debug.Print (currentA) a = a + 1 Range("b2").Select Do Until IsEmpty(ActiveCell) currentB = ActiveCell If currentA = currentB Then With Selection.Interior .Pattern = xlSolid .PatternColorIndex = xlAutomatic .ThemeColor = xlThemeColorAccent1 .Color = 65535 .PatternTintAndShade = 0 .TintAndShade = 0 End With End If Debug.Print (currentA) ActiveCell.Offset(1, 0).Select Loop Loop End Sub
下面是你的问题的一个可能的解决scheme,尽可能地使用你的代码:
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
我做了什么:
- 单元格和范围被引用到Activesheet中。
- 我已经更新了循环,所以他们看起来更好。
- 我做了一个特殊的
PaintMe
,绘制左侧和右侧的列。 - 我已经避免使用ActiveCell,因为它是缓慢和困难 – 在这里看到更多 – 如何避免使用Excel中selectVBAmacros
这是一个输出示例:
一般来说,像这样的解决scheme是非常不专业的,因为它具有n 2的algorithm复杂度 ,这可能是这类问题的最坏情况。 你有两个循环内相互,这是最慢的可能的解决scheme。 总的来说,有更好的方法来做到这一点。 但是对于excel,它应该工作。
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