找到与另一个单元格的值匹配的单元格后,选择偏移范围

时间:2019-09-06 09:22:58

标签: excel vba

我的代码有问题,因为在运行代码“对象变量或未设置块变量”时返回错误。我试过为此找到一个修复程序,并认为它与Set命令有关,但我不知道。我对VBA代码还不太满意。还在学习。

Sub FindAndDeleteRange()

Dim rFound As Range
Dim newRange As Range

RowNmbrSumDel = ThisWorkbook.Sheets("Sheet3").Range("W3").Value + 2
Set rFound = Range("A:A").Find(What:=Range("R2").Value, LookIn:=xlValues, lookat:=xlWhole)
Set newRange = Range(rFound, rFound.Offset(RowNmbrSumDel, 10))

If rFound Is Nothing Then
MsgBox "Cannot find that year to delete." & Chr(10) & "Please check you have entered correctly.", , "Error"
ElseIf Not rFound Is Nothing Then
newRange.Select
End If

End Sub

如您所愿,我希望它从R2中某个地方的column A中查找值。如果这样,则选择newRange中定义的范围,但如果不显示错误Msgbox。我真的不知道这是怎么回事。在将msgbox添加到其中之前,我确定它在某种程度上可以正常工作,但不记得它是如何工作的。任何帮助表示赞赏。

另外:我知道它是一个删除子。我只是在尝试选择。它将进行更多更改,但我需要先克服此错误。

1 个答案:

答案 0 :(得分:1)

  

设置newRange = Range(rFound,rFound.Offset(RowNmbrSumDel,10))

由于rFound一无是处,您正在尝试使用rFound来设置newRange

移动ElseIf部分中的行。您还必须对newRange进行此操作。

也请避免使用.Select。您可能需要查看How to avoid using Select in Excel VBA

这是您要实现的目标吗?

Sub FindAndDeleteRange()
    Dim rFound As Range
    Dim newRange As Range

    RowNmbrSumDel = ThisWorkbook.Sheets("Sheet3").Range("W3").Value + 2

    Set rFound = Range("A:A").Find(What:=Range("R2").Value, _
                 LookIn:=xlValues, lookat:=xlWhole)

    If rFound Is Nothing Then
        MsgBox "Cannot find that year to delete." & Chr(10) & _
        "Please check you have entered correctly.", , "Error"
    ElseIf Not rFound Is Nothing Then
        Set newRange = Range(rFound, rFound.Offset(RowNmbrSumDel, 10))

        '~~> Now Check if newRange is not nothing
        If Not newRange Is Nothing Then
            With newRange
                '~~> Do Something
            End With
        Else
            MsgBox "Cannot find.. your message here..."
        End If
    End If
End Sub