VBA - 范围:“运行时错误'91'

时间:2014-03-13 12:16:17

标签: excel excel-vba range vba

如果未保存并关闭并重新打开工作簿, 我收到以下错误

  

“运行时错误'91':对象变量或未设置块”

我在其他地方有完全相同的代码(只有字符串的名称不同),有时它会给我相同的错误,直到我保存关闭并重新打开并重新运行。之后,代码运行顺利。

关于如何避免这个bug的任何想法?你以前遇到过这个问题吗?

Dim fal As Excel.Worksheet
Set fal = wb.Sheets("Falancs")

Dim x As String
x = "F_1 ="

Dim cc As Integer ' The column as an integer (cc = 1,2,3...)
cc = fal.UsedRange.Find(x).Column

错误出现在最后一行,其中“(x)”是......

1 个答案:

答案 0 :(得分:1)

如果找不到.Find的值,则

Nothing会返回x,因此您应该检查它:

Dim fal As Excel.Worksheet
Set fal = wb.Sheets("Falancs")

Dim x As String
x = "F_1 ="

Dim cc As Integer ' The column as an integer (cc = 1,2,3...)
Dim res As Range

Set res = fal.UsedRange.Find(x)
If Not res Is Nothing Then
    cc = res.Column
Else
    MsgBox "Value " & x & " not found"
    Exit Sub
End If