在Excel VBA中查找单元格值

使用:Excel 2007 / Win 7

首先,我创build了一个子程序来查找名为“WIP”的工作表的dynamic范围:

Sub GetWIPRange() Dim WIPrng1 As Range Dim WIPrng2 As Range Sheets("WIP").Activate Set WIPrng1 = Cells.find("*", [a1], , , xlByRows, xlPrevious) Set WIPrng2 = Cells.find("*", [a1], , , xlByColumns, xlPrevious) If Not WIPrng1 Is Nothing Then Set WIPrng3 = Range([a1], Cells(WIPrng1.Row, WIPrng2.Column)) Application.Goto WIPrng3 Else MsgBox "sheet is blank", vbCritical End If End Sub 

现在我想在上面定义的范围内find给定的合同号码:

 Sub find() Dim find As Long find = Application.WorksheetFunction.Match("545499", Range(WIPrng3.Parent.Name & "!" & WIPrng3.Address), 0) MsgBox "Found at row : " & find End Sub 

但是我从上面的代码中得到的错误是:

运行时错误“91”:对象variables未设置块variables。

  1. 我怎样才能修复这个代码,以便它返回我正在寻找的值的行号?
  2. 有没有更有效的方法来find使用VBA的单元格值? 例如,如果我有很多工作表,并且想要search所有工作表并返回值的特定行号和工作表位置。

非常感谢!

WIPrng3在哪里定义? 它被定义为公共? 问题是,当你运行“查找”的时候WIPrng3已经超出了范围,因此没有。 您可以在“查找”代码中检查Nothing,并根据需要运行Get过程。 喜欢这个

 Sub find() Dim find As Long If WIPrng3 Is Nothing Then GetWIPRange find = Application.WorksheetFunction.Match("545499", Range(WIPrng3.Parent.Name & "!" & WIPrng3.Columns(1).Address), 0) MsgBox "Found at row : " & find End Sub 

需要注意两点:如果WIPrng3返回一个多列范围,则MATCH将失败并显示1004错误。 MATCH只能在单个列或行上工作。 在上面的例子中,我将WIPrng3限制在MATCH函数的第一列,以避免这种情况。 你没有在你的代码中。

另一件事是,你正在寻找文本string“545499”,而不是数字545499.如果你的范围包含数字而不是string,你会得到一个错误。 您可以使用On Error语句来捕获该错误,并进行适当的处​​理。

最后,我没有看到定义WIPrng3的好处(但是我看不到你正在做什么)。 你可以很容易地使用

 Sub Find2() Dim lRow As Long On Error Resume Next lRow = Application.WorksheetFunction.Match("545499", Sheets("WIP").UsedRange.Columns(1), 0) If lRow > 0 Then 'add where the used range starts in case it's not row 1 MsgBox "Found at row : " & lRow + Sheets("WIP").UsedRange.Cells(1).Row - 1 Else MsgBox "Not found" End If End Sub 

你可能会看到一个更大的范围,但它不会明显影响性能。

我在这个例子中添加了On Error,所以你可以看到它是如何工作的。 不要把On Error放在那里,直到你testing了它,因为它会掩盖所有其他的错误。

查尔斯·威廉姆斯在这里find了效率很高的分析http://fastexcel.wordpress.com/2011/10/26/match-vs-find-vs-variant-array-vba-performance-shootout/