我想找到一个关键字,然后对其执行操作。
Dim ws as Worksheet
Dim LastRow As Long
Dim NextRow as Long
Set ws = ActiveWorkbook.ActiveSheet
LastRow = ws.Range("A:A").Find(What:="", After:=Range("A10")).Row
NextRow = ws.Range("A:K").Find(What:="This City Is:").Row
ws.Cells(LastRow, 1) = Me.tbTextbox1.Value
ws.Cells(LastRow, 2) = Me.tbTextbox1.Value
ws.Cells(LastRow, 3) = Me.tbTextbox3.Value
ws.Cells(NextRow, 4) = "This City is: " + Me.tbTextbox4.Value
End Sub
我遇到问题的部分是 NextRow。
NextRow = ws.Range("A:K").Find(What:="This City Is:").Row
它在说
"Object variable or With Block variable not set"
我试图让 Textbox4 行在文本“This City Is:”所在的任何地方都相等。因为有时如果我决定在某处插入一行,我仍然希望代码遵循这个术语。
最佳答案
NextRow = ws.Range("A:K").Find(What:="This City Is:").Row
您假设
Range.Find
会找到它正在寻找的东西......但它没有。所以
.Row
成员(member)电话违反Nothing
, 因为 Range.Find
返回 Nothing
当它找不到它正在寻找的东西时。任何针对 Nothing
的成员(member)调用将引发错误 91。从不 使用
Range.Find
的返回值没有先验证它。捕获 Range
中的返回值引用:Dim result As Range
Set result = ws.Range("...").Find(...)
然后确保它不是
Nothing
:If Not result Is Nothing Then
NextRow = result.Row
...
End If
请注意 Rubberduck (我管理的免费开源 VBIDE 插件项目)警告这种(以及许多其他)情况:
关于excel - .Range ("...").Find 生成对象变量或未设置 block 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57776797/