我对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)]
答案 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
我做了什么:
PaintMe
,用于绘制左侧和右侧列。这是输出的样本:
一般来说,像这样的解决方案非常专业,因为它有一个algorithm complexity of n²,这可能是这种问题的最坏情况。你有2个循环,这是最慢的解决方案。总的来说,有更好的方法可以做到这一点。但是对于excel,它应该有用。