【发布时间】: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 内置函数
INDEX和MATCH来获得相同的结果会更容易和更快(如果我正确理解您的代码)。你可能想看看这篇文章:mbaexcel.com/excel/why-index-match-is-better-than-vlookup -
@CuberChase
.Columns(fCol).Rows(row)没有任何问题。这一行的唯一问题是row是Range,而不是Integer