比较细胞与阵列

时间:2017-06-30 06:51:50

标签: vba excel-vba excel

我想将从某个列中取出的数组中的值与另一列的值进行比较

但我收到错误"下标超出范围" 有更好的方法吗?

Dim start As Integer
Dim SrchRngzc As Range, cel As Range, SrchRngyx As Range, cel2 As Range
Set SrchRngzc = Range("zc16:zc500")
Set SrchRngyx = Range("yx16:yx100")
Dim x As Integer, a As Integer, b As Integer, c As Integer
Dim y As Integer
Dim n As Integer
Dim arr(1 To 85) As String
Dim num(1 To 85) As Integer

y = 1
c = 1

'highlight cells that matches
For Each cel In SrchRngyx
    arr(y) = cel.Value
    y = y + 1
Next cel

For Each cel2 In SrchRngzc
    n = 1
    For c = 1 To y
        If arr(n) = cel2.Value Then  ' error occurs here
            cel2.Interior.ColorIndex = 4
            n=n+1
            Exit For
        End If
    Next c
Next cel2

2 个答案:

答案 0 :(得分:1)

下面的代码有1个For来遍历列#34; ZC"中的所有单元格,然后每个单元格检查列中的某个位置是否匹配" YC" ,使用Application.Match

<强> 代码

Option Explicit

Sub MatchColumns()

Dim SrchRngzc As Range, Cel As Range, SrchRngyx As Range

Set SrchRngzc = Range("ZC16:ZC500")
Set SrchRngyx = Range("YX16:YX100")

' loop thorugh cells in column "ZC"
For Each Cel In SrchRngzc
    ' check if courrent value in column "ZC" has a match in column "YX"
    If Not IsError(Application.Match(Cel.Value, SrchRngyx, 0)) Then
        Cel.Interior.ColorIndex = 4
    End If
Next Cel

End Sub

答案 1 :(得分:1)

您在第一个For结束时将y设置为86。 。 。下一个循环。当您尝试访问arr(86)时,您会收到错误消息。而是尝试

y=0

For Each cel in SrchRngyx
   y = y+ 1
   arr(y) = cel.value
Next

这仍然从1开始,但在85结束。