【问题标题】:VBA Excel: User Defined FunctionVBA Excel:用户定义函数
【发布时间】:2015-08-12 08:08:03
【问题描述】:

已修复:查看 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

结束函数

【问题讨论】:

  • 怎么不工作?另外,请不要养成使用 goto 的习惯。还有其他更好的退出循环的方法。在这种情况下,您可以使用 VBA 退出循环构造 Exit For 而不是 goto。另一种选择是在循环内设置asda = rng.Columns(rCol, row).Value,然后使用Exit Function
  • 嗨,感谢退出。出于某种原因,它只返回#value。
  • 你不能串起来.Columns(fCol).Rows(row)试试rng.Cells(row, fCol).Value
  • 不要误会我的意思。我也喜欢玩一些自定义函数。但在这种情况下,使用 Excel 内置函数 INDEXMATCH 来获得相同的结果会更容易和更快(如果我正确理解您的代码)。你可能想看看这篇文章:mbaexcel.com/excel/why-index-match-is-better-than-vlookup
  • @CuberChase .Columns(fCol).Rows(row) 没有任何问题。这一行的唯一问题是rowRange,而不是Integer

标签: vba excel excel-udf


【解决方案1】:

第一个解释请看 cmets。

当您使用 row 作为变量时,您无法从 Range 类 调用 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

【讨论】:

  • 这其实很干净优雅。谢谢。
  • 谢谢,不客气!但请记住避免使用可能已经在 VBA 中经典使用的名称以避免此类问题! ;)
猜你喜欢
  • 2011-02-06
  • 1970-01-01
  • 2013-08-13
  • 1970-01-01
  • 1970-01-01
  • 2019-12-19
  • 1970-01-01
  • 1970-01-01
  • 2017-03-04
相关资源
最近更新 更多