VBA Excel:使用 Range.Find 方法时出现错误 1004 [英] VBA Excel: error 1004 when using Range.Find method

查看:82
本文介绍了VBA Excel:使用 Range.Find 方法时出现错误 1004的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习 Range.Find 方法.我在 Excel 的 A 列中有一列字母(a 到 t),从第 1 行到第 20 行.

I am learning about the Range.Find method. I have a column of letters (a to t) in column A of Excel, from row 1 to row 20.

此代码:

Public Sub MyFind3()

'Accepts an input for a fluid length search field (column A)
Dim WhatToFind As String
Dim DataRange As Range

Set DataRange = Range("A1", Range("A1").End(xlDown))
WhatToFind = InputBox("Enter text to search for:", "Find Text")
Range(DataRange).Find(WhatToFind).Select

End Sub

...当我收到此错误时,一直工作到最后一行:运行时错误 1004:应用程序定义或对象定义的错误".它没有找到 Find 匹配项.谁能指出我的错误?非常感谢.

...works up to the last line when I get this error: "Run-time error 1004: Application-defined or object-defined Error". It does not find the Find match. Can anyone point out my error please? Many thanks.

推荐答案

.Find() 返回您通常希望分配给范围变量的范围.我会像这样稍微修改你的代码:

.Find() returns a range that you'll usually want to assign to a range variable. I would rework your code slightly like this:

Public Sub MyFind3()

'Accepts an input for a fluid length search field (column A)
Dim WhatToFind As String
Dim DataRange As Range

WhatToFind = InputBox("Enter text to search for:", "Find Text")
Set DataRange = Range("A1", Range("A1").End(xlDown)).Find(What:=WhatToFind)
if not DataRange is Nothing then
  DataRange.select
else
  msgbox (WhatToFind & " wasn't found")
end if

End Sub

这为您提供了能够处理未找到"条件的优势,并且您有一个范围变量,您现在可以用它做其他事情.

That gives you the advantage of being able to handle the 'not found' condition, and you have a range var you can now do something else with.

另外,请注意,当您调用 .Find() 时,它将使用最后的设置执行,因此设置更多参数,例如 LookInLookAtMatchCase 将有助于确保此搜索完全按照您的预期工作.

Also, be aware that when you call .Find(), it will execute with whatever the last settings were, so setting more of the parameters, such as LookIn, LookAt, and MatchCase will help ensure that this search works exactly as you intend.

这篇关于VBA Excel:使用 Range.Find 方法时出现错误 1004的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆