繁体   English   中英

Excel VBA-在数组之间匹配值

[英]Excel VBA - matching value from array to array

我正在比较2数组。 1是动态数组,1是静态数组,都是大小不同的一维数组。 条件是,如果动态数组中的值与静态数组中的值匹配,则它将采用单元格值,并且将发生其他操作。

示例案例:

dynArr = (123,123,45,23,56,90,34,Nil) ' size based on row counts
staArr = (90,60,30,0)

因此,如果dynArr中的任何值与dynArr匹配, staArr发生某些情况。

现在,我认为我的情况出了问题,因为它从excel行中获取了所有值。

我尝试使用application.match()但从msdn的描述来看,它似乎不起作用,并且就速度而言,它比其他 一些 文章要慢得多。

如何更改条件以在阵列之间匹配? 或有什么解决方法?

Sub getValue()

'define dynamic array
Dim sn, sb, interval, daysleft As Variant
'define static array
interval = Array(90, 60, 30, 14, 7, 0, -2)

Dim cnt As Long
Dim i, x, y As Long

ReDim sn(1 To 1)
ReDim sb(1 To 1)
ReDim daysleft(1 To 1)

cnt = 0

'Loop through all the row
For i = 1 To Cells(Rows.Count, "L").End(xlUp).Row
    'redim daysleft based on the rows
    ReDim Preserve daysleft(1 To i)
    daysleft(i) = Cells(i, "L").Value

    For x = LBound(daysleft) To UBound(daysleft)
     For y = LBound(interval) To UBound(interval)

        If daysleft(x) = interval(y) Then 'Loops everything

            'assign cell value to array
            cnt = cnt + 1
            ReDim Preserve sn(1 To cnt)
            ReDim Preserve sb(1 To cnt)

            sn(cnt) = Cells(i, "A").Value
            sb(cnt) = Cells(i, "F").Value

         End If
        Next y
    Next x
Next i

For i = 1 To (cnt - 1)
    Debug.Print "This is sn: "; sn(i) 'gets all the value instead of the matching case
  'Call test(sn(i), sb(i))
Next

End Sub

好。 我想这就是你想要的。 我注释掉了For x循环。 您拥有的i循环将剩余所有天数加载起来。 使用x循环会导致您在间隔中多次匹配相同的值。

Sub getValue()

    'define dynamic array
    Dim sn, sb, interval, daysleft As Variant
    'define static array
    interval = Array(90, 60, 30, 14, 7, 0, -2)

    Dim cnt As Long
    Dim i, x, y As Long

    ReDim sn(1 To 1)
    ReDim sb(1 To 1)
    ReDim daysleft(1 To 1)

    cnt = 0

    ' Loop through all the row
    For i = 1 To Cells(Rows.Count, "L").End(xlUp).row
        'redim daysleft based on the rows
        ReDim Preserve daysleft(1 To i)
        daysleft(i) = Cells(i, "L").Value

        'For x = LBound(daysleft) To UBound(daysleft)
            For y = LBound(interval) To UBound(interval)

               If daysleft(i) = interval(y) Then 'Loops everything

               'assign cell value to array
               cnt = cnt + 1
               ReDim Preserve sn(1 To cnt)
               ReDim Preserve sb(1 To cnt)

               sn(cnt) = Cells(i, "A").Value
               sb(cnt) = Cells(i, "F").Value

            End If
            Next y
         'Next x
     Next i

     For i = 1 To (cnt)
          Debug.Print "This is sn: "; sn(i) 'gets all the value instead of the matching case
         'Call test(sn(i), sb(i))
     Next

End Sub

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM