[英]Run-time error '1004' : Method 'Range' of object'_Global' failed
[英]Run-time error 1004 - Method 'Range' of object'_Global' failed
我想獲取.xlsx
文件中A列和B列的數據,並將它們粘貼到活動的Workbook
,從BS
和BT
列開始,從第6行開始。
這是我在宏的其他部分中一直使用的代碼:
Workbooks.Open ThisWorkbook.Path & "\..\macro\options.xlsx"
Workbooks("options.xlsx").Activate
Set c = .Find("licensePlate", LookIn:=xlValues)
Range(c.Offset(1, 0), Range(c.Address).End(xlDown)).Copy
ThisWorkbook.Activate
Sheets("example").Activate
Range("BS6").PasteSpecial Paste:=xlPasteValues
Workbooks("options.xlsx").Activate
Set c = .Find("description", LookIn:=xlValues)
Range(c.Offset(1, 0), Range(c.Address).End(xlDown)).Copy
ThisWorkbook.Activate
Sheets("example").Activate
Range("BT6").PasteSpecial Paste:=xlPasteValues
Workbooks("options.xlsx").Close
ThisWorkbook.Activate
它適用於所有宏內容,除了這部分代碼。 它在第5行失敗,該行是:
(Range(c.Offset(1, 0), Range(c.Address).End(xlDown)).Copy)
您.Find
似乎不是在指范圍,因為您沒有在使用With Range
。 因此,將c
設置為Nothing
並且當您嘗試Offset
Nothing Range
時會出現錯誤。
您需要使用類似的錯誤檢查
If c is Nothing Then
Msgbox "licensePlate Not Found"
Else
'Run Code
End If
如果要搜索整個工作表,可以使用類似以下內容的方法:
Set c = Workbooks("options.xlsx").Sheets("name of sheet").Cells.Find("licensePlate", LookIn:=xlValues)
If c is Nothing Then
Msgbox "licensePlate Not Found"
Else
'Run Code
End If
另外,我強烈建議您避免使用Activate
。 相反,您應該始終在上定義使用方法的對象 。
編輯:您也沒有為Range
定義圖紙:
這樣的事情應該起作用:
Dim ws1 as Worksheet, Dim c As Range
Set ws1 = Workbooks("options.xlsx").Sheets("name of sheet")
Set c = ws1.Cells.Find("licensePlate", LookIn:=xlValues)
If c is Nothing Then
Msgbox "licensePlate Not Found"
Else
ws1.Range(c.Offset(1, 0), c.End(xlDown)).Copy
ThisWorkbook.Sheets("example").Range("BS6").PasteSpecial Paste:=xlPasteValues
End If
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.