VBA Excel:用户定义的函数

时间:2015-05-29 12:40:42

标签: excel vba excel-vba excel-udf

已修复:查看用户3964075的评论

需要以下简单代码的帮助: 它基本上是vlookup的不同版本,您还可以指定要查找的行。

asda(fval,rng,fcol,rcol)

fval 是用户正在寻找的内容

rng 是范围

fcol 是通过vlookup默认设置为1,现在用户可以选择要用作搜索基础的列

rcol 是找到匹配时将返回的列

见下面的代码:

Function asda(fval As Range, rng As Range, fCol As Integer, rCol As Integer)

    Dim row As Variant

    For Each row In rng.Rows
        If fval.Value = rng.Columns(fCol).Rows(row).Value Then
            result = rng.Columns(rCol).Rows(row).Value
            GoTo found
        End If
    Next

found:
    asda = result

End Function

问题:它不起作用,我不知道为什么。 由于我想使用其他人的代码,我想从我的开始并修复它。

修改了以后阅读此内容的人的代码:

Function asda(fval As Range, rng As Range, fCol As Integer, rCol As Integer)
Dim row As Variant
Dim rowc As Integer

rowc = 1
For Each row In rng.Rows
    If fval.Value = rng.Cells(rowc, fCol).Value Then
        result = rng.Cells(rowc, rCol).Value
        Exit For
    End If
    rowc = rowc + 1
Next

asda= result

结束功能

1 个答案:

答案 0 :(得分:0)

请看第一次解释的评论。

当您使用row作为变量时,您无法从范围类调用行属性,因此我将其更改为RowV使用RowV.row

汇编所说的内容:

Function asda(fval As Range, rng As Range, fCol As Integer, rCol As Integer)

    Dim RowV As Range

    For Each RowV In rng.Rows
        If fval.Value <> rng.Cells(RowV.row, fCol).Value Then
        Else
            asda = rng.Columns(rCol).Rows(RowV.row).Value
            'Exit For
            Exit Function
        End If
    Next RowV

    asda = "Value not found"

End Function