2017-04-21 105 views
1

我是VBA的新手,并且在找到我需要的答案方面相当成功,直到现在。我想在列A中取一个值,看看它是否出现在列B中,并在找到该值时执行一个操作,然后转到列B中的下一列。我觉得我很近,只是没有找到正确的东西。试图比较列a中的单元格与列b中的单元格vba

这里是我已经试过到目前为止

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 
+0

你能描述什么不工作?它做什么,它应该做什么? –

+0

@RichHolton说,请你介绍一下哪些工作不正常? –

回答

0
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 
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. 单元格和范围被引用到th e带有点的Activesheet。
  2. 我已经更新了循环,所以它们看起来更好。
  3. 我做了一个特殊的子PaintMe,它描绘了左侧和右侧的列。
  4. 我避免使用ActiveCell,因为它是缓慢而艰难的 - 看到更多的在这里 - How to avoid using Select in Excel VBA macros

这是输出的一个样本:

enter image description here

在一般情况下,这样的解决方案是相当不专业的,因为它有一个algorithm complexity of n²,这可能是这种问题的最坏情况。你有两个循环内相互,这是最慢的解决方案。一般来说,有更好的方法可以做到这一点。但对于excel来说,它应该起作用。

相关问题