vba 运行时错误 1004 - 对象 '_Global' 的方法 'Range' 失败
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28070031/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Run-time error 1004 - Method 'Range' of object'_Global' failed
提问by smt
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.
我想获得A的数据和B柱内的.xlsx
文件,并将其粘贴在活动Workbook
,在这两个BS
和BT
列,开始于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:
除了这部分代码之外,它适用于所有宏内容。它在第 5 行失败,即:
(Range(c.Offset(1, 0), Range(c.Address).End(xlDown)).Copy)
(Range(c.Offset(1, 0), Range(c.Address).End(xlDown)).Copy)
回答by Chrismas007
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.
您.Find
似乎不是指范围,因为您没有使用With Range
. 因此,c
正在设置为Nothing
,当您尝试使用Offset
a 时,Nothing Range
您将收到错误消息。
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.
另外,我强烈建议您避免Activate
. 相反,您应该始终定义使用方法的对象。
Edit: You aren't defining your Sheet for the Range
either:
编辑:您没有为以下Range
任一定义您的工作表:
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