运行-时间错误 1004 - 对象“_Global”的方法 'Range' 失败

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

我想获取 .xlsx 文件中 A 和 B 列的数据,并将它们粘贴到活动的 Workbook 中,在 BS 和 [=16= 中] 列,从第 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,当您尝试 OffsetNothing Range 时,您将收到错误消息。

你需要使用像

这样的错误检查
If c is Nothing Then
    Msgbox "licensePlate Not Found"
Else
    'Run Code
End If

如果你想搜索整个 sheet 你可以使用类似的东西:

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。相反,您应该 always define the object that you are using a method on.

编辑:您也没有为 Range 定义 Sheet:

像这样的东西应该可以工作:

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