VBA检查搜索值是否为某种东西

时间:2016-03-17 11:06:32

标签: excel excel-vba macros vba

我有一个宏来添加和删除数据库的客户端。如果客户端存在于数据库中,我希望能够停止,如果不存在,则继续。如果客户端已存在,则以下情况有效:

Dim newClient As String, foundRange As Range
newClient = Sheets("Summary").Range("K2").Value

'check if client exists

Set foundRange = Sheets("Per Client").Cells.Find(what:=newClient, After:=ActiveCell, LookIn:=xlFormulas, lookat _
    :=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
    False, SearchFormat:=False)

If foundRange = newClient Then
    MsgBox "Client " & newClient & " already exists."
    GoTo finishUp
End If

'add new client
'code continues here'

目前,如果客户端确实存在,则foundRange确实等于newClient,并且用户获取消息,并且宏跳转到finishUp。但是如果foundRange = Nothing,我会得到

Object variable or With block variable not set

错误。

这是唯一一次在宏中调用foundRange。解决这个问题的最佳方法是foundRange = Nothing

2 个答案:

答案 0 :(得分:1)

如果没有找到单元格,

foundRange将确实等于Nothing

您可以按如下方式检查:

If Not foundRange is Nothing Then MsgBox "Client " & newClient & " already exists." GoTo finishUp End If

答案 1 :(得分:1)

好的我用If Not Nothing

计算出来了
If Not foundRange Is Nothing Then
    MsgBox "Client " & newClient & " already exists."
    GoTo finishUp
End If