MyArray = Array("Jap", "Mcdonalds", "Chinese", "Pasta")
我正在尝试做一个IF功能,如果MyArray在阵列上,那么中文'但是当我做的时候
If MyArray("Jap") Then ....
它出现了错误。我该怎么做呢?
答案 0 :(得分:0)
许多方法可以做到这一点,这是一个。
Sub x()
Dim MyArray, i As Long
MyArray = Array("Jap", "Mcdonalds", "Chinese", "Pasta")
For i = LBound(MyArray) To UBound(MyArray)
If MyArray(i) = "Jap" Then
'do whatever
End If
Next i
End Sub
答案 1 :(得分:0)
你需要遍历数组:
MyArray = Array("Jap", "Mcdonalds", "Chinese", "Pasta")
for i = lbound(MyArray) to UBound(MyArray)
if MyArray(i) = "Jap" then
'do whatever
End If
Next
答案 2 :(得分:0)
如果你想测试一个项目是否在一个数组(一维)中,你可以使用Filter()
:
Sub dural()
MyArray = Array("alpha", "beta", "gamma")
x = Filter(MyArray, "alpha")
y = Filter(MyArray, "junk")
MsgBox UBound(x) & vbCrLf & UBound(y)
End Sub
无需循环。
答案 3 :(得分:0)
其他一些避免循环的方法
Sub NoLoop1()
CMyArray = Array("Jap", "Mcdonalds", "Chinese", "Pasta")
If Not IsError(Application.Match("Jap", MyArray,0))
‘ your code
End If
End Sub
Sub NoLoop2()
CMyArray = Array("Jap", "Mcdonalds", "Chinese", "Pasta")
If Instr("-" & Join(MyArray, "-") & "-", "-Jap-") > 0 Then
‘ your code
End If
End Sub