在 VBA 中使用 application.match 时出现错误 2042
Error 2042 when using application.match in VBA
我试图在 VBA 的数组中找到整数的索引。
我是这样创建数组的。
Dim spot(11) as Integer
For index = 1 To NoOfSpotValues
spot(index) = Cells(15 + index, 7)
Next
当我这样做时:
posOfSpot = Application.Match(0, spot, False)
它给我一个错误
posOfSpot = Error 2042
.
我该如何解决?尝试搜索。需要一些指导。
编辑:
Function Find(ByVal Value As Variant, arr As Variant) As Integer
If arr.Exists(Value) Then
index = arr(Value)
Else
index = -1
End If
如果您愿意使用公式而不是 VBA,您可以
=MATCH(0 ,G16:G26,0)
如果找不到该值,它将 return #N/A
,否则索引。
Sub Find(ByVal Value As Integer)
Dim spotData
Dim index As Integer
Set spotData = CreateObject("Scripting.Dictionary")
For index = 1 To 11
spotData.Add Cells(15 + index, 7).Value, index
Next
If spotData.Exists(Value) Then
index = spotData(Value)
Else
index = -1
End If
Set spotData = Nothing
Debug.Print index
End Sub
Dim spot(1 to 11) as Long
Dim posOfSpot& , index&
For index = 1 To NoOfSpotValues
spot(index) = Cells(15 + index, 7).value
Next index
posOfSpot = Application.Match(0, spot, 0)
msgbox posOfSpot
试过了,有效。
但是,如果在数组中使用一个简单的循环来查找您的值,代码会更快
我试图在 VBA 的数组中找到整数的索引。
我是这样创建数组的。
Dim spot(11) as Integer
For index = 1 To NoOfSpotValues
spot(index) = Cells(15 + index, 7)
Next
当我这样做时:
posOfSpot = Application.Match(0, spot, False)
它给我一个错误
posOfSpot = Error 2042
.
我该如何解决?尝试搜索。需要一些指导。
编辑:
Function Find(ByVal Value As Variant, arr As Variant) As Integer
If arr.Exists(Value) Then
index = arr(Value)
Else
index = -1
End If
如果您愿意使用公式而不是 VBA,您可以
=MATCH(0 ,G16:G26,0)
如果找不到该值,它将 return #N/A
,否则索引。
Sub Find(ByVal Value As Integer)
Dim spotData
Dim index As Integer
Set spotData = CreateObject("Scripting.Dictionary")
For index = 1 To 11
spotData.Add Cells(15 + index, 7).Value, index
Next
If spotData.Exists(Value) Then
index = spotData(Value)
Else
index = -1
End If
Set spotData = Nothing
Debug.Print index
End Sub
Dim spot(1 to 11) as Long
Dim posOfSpot& , index&
For index = 1 To NoOfSpotValues
spot(index) = Cells(15 + index, 7).value
Next index
posOfSpot = Application.Match(0, spot, 0)
msgbox posOfSpot
试过了,有效。
但是,如果在数组中使用一个简单的循环来查找您的值,代码会更快