Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/excel/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用instr vba excel的索引匹配组合的自定义项_Vba_Excel_Excel Formula - Fatal编程技术网

使用instr vba excel的索引匹配组合的自定义项

使用instr vba excel的索引匹配组合的自定义项,vba,excel,excel-formula,Vba,Excel,Excel Formula,我为一个UDF编写了这段代码,但是当我在许多单元格中使用它时,计算起来要花很多时间。有没有更有效的方法 Public Function AGSIndexMatch(result_column As Range, lookup As Range, _ lookup_column As Range) As Variant Dim cel As Range Dim b As String Di

我为一个UDF编写了这段代码,但是当我在许多单元格中使用它时,计算起来要花很多时间。有没有更有效的方法

Public Function AGSIndexMatch(result_column As Range, lookup As Range, _
                                           lookup_column As Range) As Variant
    Dim cel As Range
    Dim b As String
    Dim i As Variant
    i = 1
    For Each cel In lookup_column
        On Error GoTo error_handler:
        If Not IsEmpty(cel) Then
            If InStr(1, cel.Value, lookup) <> 0 Then
                AGSIndexMatch = AGSIndexMatch & Application _
                  .WorksheetFunction.Index(result_column, i, 1) & Chr(10)
            End If
        End If
        i = i + 1
    Next cel
    If Len(AGSIndexMatch) <> 0 Then
        AGSIndexMatch = Left(AGSIndexMatch, Len(AGSIndexMatch) - 1)
    End If
    Exit Function
error_handler:
    AGSIndexMatch = Err.Description
End Function
公共函数AGSIndexMatch(结果列作为范围,查找作为范围_
查找(列作为范围)作为变量
暗淡的cel As范围
将b变暗为字符串
Dim i作为变体
i=1
对于lookup_列中的每个cel
错误转到错误处理程序时:
如果不是空的(cel),那么
如果指令(1,单元值,查找)为0,则
AGSIndexMatch=AGSIndexMatch&应用程序_
.WorksheetFunction.Index(结果列,i,1)和Chr(10)
如果结束
如果结束
i=i+1
下一个细胞
如果Len(AGSIndexMatch)为0,则
AGSIndexMatch=左(AGSIndexMatch,Len(AGSIndexMatch)-1)
如果结束
退出功能
错误\u处理程序:
AGSIndexMatch=错误描述
端函数

在执行循环之前,将数据移动到一个变量数组中将大大缩短时间-多少取决于范围的大小

Public Function AGSIndexMatch( _
  result_column As Range, _
  lookup As Range, _
  lookup_column As Range) As Variant

    Dim rsc As Variant, src As Variant, lup As Variant
    rsc = result_column.Value2
    src = lookup_column.Value2
    lup = lookup.Value2
    Dim i As Long
    Dim res As String

    On Error GoTo error_handler:
    For i = 1 To UBound(src, 1)
        If src(i, 1) = lup Then
            res = res & Chr(10) & rsc(i, 1)
        End If
    Next
    AGSIndexMatch = Mid$(res, 2)

Exit Function
error_handler:
    AGSIndexMatch = Err.Description
End Function

根据您数据的性质,可能还有其他更好的方法

您是说这一切都很好(没有具体问题),您想听听如何提高效率的建议吗?如果是这样,这可能不是你的正确位置。有关此网站主题的详细信息,以及“”和如何创建。提出问题以提高工作代码的效率可能更适合作为问答网站,以寻求同行对您的代码进行审查。@ashleedawg,然后建议转到CRD。非常感谢!这大大缩短了时间。我更改了if语句以更好地满足我的需要。->如果InStr(1,src(i,1),lup)0,那么我必须在For之前加上If Not IsEmpty(lup),因此如果lup为空,它不会进行任何计算。