2017-07-18 221 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可言,相反,適當資格的範圍。

相關問題