[英]Excel VBA macro: Locating first empty cell in a column and automatically filling it
[英]Locating Cell Values in Excel VBA
使用:Excel 2007 / Win 7
首先,我创建了一个子例程来查找名为“ WIP”的工作表的动态范围:
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
现在,我想在上述定义的范围内找到给定的合同编号:
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':对象变量未设置块变量。
非常感谢!
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函数的第一列,以避免出现这种情况。 您的代码中没有这个。
另一件事是您正在寻找文本字符串“ 545499”,而不是数字545499。如果您的范围包含数字而不是字符串,则会出现错误。 您可以使用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进行测试之前,不要在其中放置它,因为它将掩盖所有其他错误。
查尔斯·威廉姆斯(Charles Williams)在这里找到了一些关于效率发现的很好的分析, 网址为http://fastexcel.wordpress.com/2011/10/26/match-vs-find-vs-variant-array-vba-performance-shootout/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.