嘿,也许我在这里没有看到明显的东西,但是如何使用带有预定义变量的 Find VBA 函数。我正在使用从用户表单分配的字符串的串联,并且在它前面只有“total”,但我无法返回该行。
下面是我的代码
Dim HBWS As Worksheet
Dim TickerString As String
TickerString = "Total " & TTB
Set HBWS = Sheets("Hoenheimm Worksheet")
BorrowColumn = HBWS.Cells.Find(What:="Borrow").Column 'Works just fine
TickerRow = HBWS.Cells.Find(What:=TickerString).Row 'Throws an error
请注意,TTB 设置为股票代码 ex。 AAPL,我可以在我的本地窗口中检查 Tickerstring 实际上 = “Total AAPL”
我希望 .Row 列能够在我的工作表上为我提供关于该字符串所在位置的行。
编辑:抛出的错误如下......
"Run-Time error '91':
Object Variable or With block variable not set"
任何穿越,
谢谢
最佳答案
您正在调用 Range.Find
.该方法返回 Range
对象引用 - 当它没有找到它被告知要查找的内容时,它返回 Nothing
,即空引用。
TickerRow = HBWS.Cells.Find(What:=TickerString).Row 'Throws an error
这段代码在做什么(以及它上面的工作指令)假设
Find
返回一个有效的对象引用。显然
HBWS.Cells
不包含 "Total " & TTB
(无论 TTB
是什么),因此您的代码实际上是在尝试调用 Range.Row
反对 Range
引用是 Nothing
...这是非法的,并且会在您遇到时引发运行时错误 91。你不应该假设
Find
将永远返回一个有效的引用。将其拆分,并使用 If ... Is Nothing
验证返回的对象引用查看:Set tickerResult = HBWS.Cells.Find(What:=TickerString)
If Not tickerResult Is Nothing Then
tickerRow = tickerResult.Row
Else
'tickerString was not found.
'watch for leading/trailing/extra spaces if the string does *look* legit.
End If
调用
Range.Find
时,您应该始终为可选参数提供一个值,因为它的实现“记住”来自先前调用的值,这很容易出错。
关于vba - 使用定义字符串的 Find VBA 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49456008/