【问题标题】:.Range("...").Find generates Object variable or With Block variable not set.Range("...").Find 生成对象变量或未设置块变量
【发布时间】:2026-01-04 15:05:02
【问题描述】:

我想找到一个关键字,然后对其执行操作。

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

这是在说

“未设置对象变量或With Block变量”

我试图让 Textbox4 行在文本“This City Is:”所在的任何地方都相等。因为有时如果我决定在某处插入一行,我仍然希望代码遵循这个术语。

【问题讨论】:

  • NextRow 应声明为 Long,而不是 String
  • @DarrellH 是的,但这里的问题不太可能

标签: excel vba


【解决方案1】:
NextRow = ws.Range("A:K").Find(What:="This City Is:").Row

您假设 Range.Find 会找到它正在寻找的东西......但它没有。

所以.Row 成员调用与Nothing 相违背,因为Range.Find 在找不到所需内容时返回Nothing。任何针对 Nothing 的成员调用都会引发错误 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 插件项目)会针对这种(以及许多其他)情况发出警告:

【讨论】: