简体   繁体   中英

Run-time error 1004 - Method 'Range' of object'_Global' failed

I'd like to get the data of A and B columns inside .xlsx file, and paste them in the active Workbook , in both BS and BT columns, starting at row 6.

This is the code I've been using in other parts of the macro:

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

It worked in all of the macro content except on this portion of code. It fails at line 5, which is:

(Range(c.Offset(1, 0), Range(c.Address).End(xlDown)).Copy)

You .Find doesn't seem to be referring to a Range because you are not using a With Range . Therefore, c is being set to Nothing and when you try to Offset a Nothing Range you will get the error.

You need to use an error check like

If c is Nothing Then
    Msgbox "licensePlate Not Found"
Else
    'Run Code
End If

If you want to search a whole sheet you could use something like:

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

Also, I would highly recommend you avoid Activate . Instead, you should always define the object that you are using a method on .

Edit: You aren't defining your Sheet for the Range either:

Something like this should work:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM