簡體   English   中英

運行時錯誤1004-對象'_Global'的方法'Range'失敗

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

我想獲取.xlsx文件中A列和B列的數據,並將它們粘貼到活動的Workbook ,從BSBT列開始,從第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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM