excel vba - 在数组中搜索值

时间:2017-07-19 11:15:00

标签: excel vba

如何从数组中选择一个值,并根据条件将其写入单元格?

我有这个:

Dim Material As Variant

Dim Material1 As Variant
Material1 = Array("16", "20", "26", "32", "40", "50", "63", "70")

Dim Material2 As Variant
Material2 = Array("12", "16", "22", "28", "34", "42", "58", "65")

Dim Rows as Long
For Rows = 9 to lastrow

If Range("P"&Rows).Value <> 0 then

If Range("W"&Rows).value = Material1 then
Material = Material1
'material can be Material2 also, but I would do the same IF


If Range("Z"&Rows).Value > 2 then
Range ("X"&Rows).value = ' this is where I fail, I want to write here a value from Material1 (looping through position 1, 2, etc...)that does the opposite to my condition, i.e. <2 (this is related with formulas in the sheet)

我没有忘记&#34;结束&#34; IFs并转移到&#34; Next Rows&#34;

2 个答案:

答案 0 :(得分:0)

您正尝试将单元格的值与整个Material1数组进行比较:

If Range("W"&Rows).value = Material1 then 

如果你想检查列&#34; W&#34;等于Material1中的一个元素,您可以使用Match函数:

If Not IsError(Application.Match(Range("W" & Rows).Value, Material1, 0)) Then

答案 1 :(得分:0)

只需循环遍历数组:

For i = LBound(Materials1) To UBound(Materials1)
    'check for value using Materials(i)
Next i