VBA Excel: 用户自定义函数

VBA Excel: User Defined Function

已修复:检查 user3964075 的评论

需要以下简单代码的帮助: 它基本上是 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

结束函数

第一个解释看评论

当您使用 row 作为变量时,您无法从 范围 [=] 中调用 行 属性 24=],所以我改成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