首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在VBA中使用application.match时的错误2042

在VBA中使用application.match时的错误2042
EN

Stack Overflow用户
提问于 2015-01-16 07:30:33
回答 2查看 4.8K关注 0票数 1

我试图在VBA中的数组中找到整数的索引。

我创建了这样的数组。

代码语言:javascript
运行
复制
Dim spot(11) as Integer
For index = 1 To NoOfSpotValues
   spot(index) = Cells(15 + index, 7)
Next

当我这么做时:

代码语言:javascript
运行
复制
posOfSpot = Application.Match(0, spot, False)

它给了我一个错误作为posOfSpot = Error 2042

我该怎么解决呢?试着搜索。在这方面需要一些指导。

编辑:

代码语言:javascript
运行
复制
Function Find(ByVal Value As Variant, arr As Variant) As Integer
If arr.Exists(Value) Then
    index = arr(Value)
Else
    index = -1
End If
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-01-16 07:50:39

如果您愿意使用公式而不是VBA,您可以这样做。

代码语言:javascript
运行
复制
=MATCH(0 ,G16:G26,0)

如果找不到值,它将返回#N/A,否则返回索引。

代码语言:javascript
运行
复制
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
票数 3
EN

Stack Overflow用户

发布于 2015-01-18 00:19:23

代码语言:javascript
运行
复制
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

试过了,成功了。

但是,如果在数组中使用一个简单的循环来查找您的值,代码会更快。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27979154

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档