[英]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.