2017-07-18 222 views
0

我试图找到字符串单元格下方的范围,然后将该范围复制到另一个工作表。 我成功找到并复制范围,但由于发生错误91,无法将其粘贴到另一个工作表。我尝试了很多不同的方式,但仍然是问题。请帮助我。下面是代码:VBA:运行时错误91:对象变量或未设置块变量

Sub Copy() 

    Dim SearchRange As Range 
    Dim FindRow1 As Range 
    Dim FindRow2 As Range 
    Dim FindRow3 As Range 
    Dim a1 As Long 
    Dim a2 As Long 
    Dim b1 As Long 
    Dim b2 As Long 
    Dim c1 As Long 

    Set SearchRange = Range("A1", Range("A65536").End(xlUp)) 
    Set FindRow1 = SearchRange.Find("EUR", LookIn:=xlValues, lookat:=xlWhole) 
    Set FindRow2 = SearchRange.Find("USD", LookIn:=xlValues, lookat:=xlWhole) 
    Set FindRow3 = SearchRange.Find("VND", LookIn:=xlValues, lookat:=xlWhole) 

    a1 = FindRow1.Row + 1 
    a2 = FindRow2.Row - 1 
    b1 = FindRow2.Row + 1 
    b2 = FindRow3.Row - 1 
    c1 = FindRow3.Row + 1 

    Range(Cells(a1, "A"), Cells(a2, "AU")).Select 
    Selection.Copy 
    Sheets("Sheet1").Select 
    Selection.Paste 

End Sub 
+2

你知道whichline给出了错误? – doctorlove

+0

[查找命令给出错误:“运行时错误'91':对象变量或块变量未设置”](https://stackoverflow.com/q/26653203/11683) – GSerg

+0

错误显示在行a1 = Findrow1.Row +1 –

回答

1

使用Find函数时,需要确认Find已成功,然后再为其结果分配另一个变量。

尝试下面您尝试使用Find 3次后的代码scection:

' make sure Find was able to find all 3 strings 
If Not FindRow1 Is Nothing And Not FindRow2 Is Nothing And FindRow3 Is Nothing Then 
    a1 = FindRow1.Row + 1 
    a2 = FindRow2.Row - 1 
    b1 = FindRow2.Row + 1 
    b2 = FindRow3.Row - 1 
    c1 = FindRow3.Row + 1 

    ' Copy >> Paste in 1 line (without using Select) 
    Range(Cells(a1, "A"), Cells(a2, "AU")).Copy Destination:=Sheets("Sheet1").Range("A1") 
Else ' FInd failed in at least one of the strings 
    MsgBox "Find couldn't find at least one of the strings", vbCritical 
End If 
+0

它的工作原理!谢谢您的回答。我想我错过了如果不是部分。 –

+0

@DD欢迎您通过点击我答案左侧的灰色复选标记(它会变成绿色)来标记此为“答案”,现在来到您的部分,谢谢 –

+0

嗨,我试图修改有点自动打开文件,但又遇到了一个问题,我不明白为什么,你能帮我检查一下吗? –

-1

使用selection.pastespecial代替selection.paste

或更好,但不要用selection可言,相反,适当资格的范围。

相关问题