![](/img/trans.png)
[英]Why am I getting Run-time error '1004' with my VBA code to copy and paste from one workbook to another?
[英]Why am i getting this error with copy/paste?
我收到一個錯誤
運行時錯誤 1004:應用程序定義或對象定義錯誤
在我的 vba 代碼中。 你能幫我改正嗎?
Sub INPUT_DATA()
' INPUT_DATA Macro
' Application.ScreenUpdating = False
Application.EnableEvents = False
Sheets("Input").Select
If Range("D55").Value = 0 Then
Range("B2:AI52").Select
Selection.Copy
Sheets("Database").Select
ActiveSheet.Range("A2").End(xlDown).Offset(1, 0).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
End If
Sheets("Input").Select
MsgBox ("File has been updated. DO NOT PRESS UPDATE again, as it will enter the same data once again")
End Sub
你沒有說哪一行導致了錯誤,但看起來很可能是這一行......
ActiveSheet.Range("A2").End(xlDown).Offset(1, 0).Select
它從 A2 開始,然后向下直到找到最后使用的行。 但是,如果 A2 下方沒有任何已使用的行,它會在 A 列中找到最后一行。然后它會嘗試偏移到它下方的一行,但該行不存在,因此會出現錯誤。 相反,您可以找到下一個可用行,如下所示...
ActiveSheet.Range("A" & Rows.Count).End(xlUp).Offset(1, 0).Select
雖然,沒有必要做所有這些選擇。 這是非常低效的。 所以你的宏可以重寫如下......
Option Explicit
Sub INPUT_DATA()
' INPUT_DATA Macro
With Application
.ScreenUpdating = False
.EnableEvents = False
End With
Dim sourceWorksheet As Worksheet
Set sourceWorksheet = Worksheets("Input")
Dim destinationWorksheet As Worksheet
Set destinationWorksheet = Worksheets("Database")
With sourceWorksheet
If .Range("D55").Value = 0 Then
.Range("B2:AI52").Copy
With destinationWorksheet
.Cells(.Rows.Count, "A").End(xlUp).Offset(1, 0).PasteSpecial Paste:=xlPasteValues
End With
End If
End With
With Application
.ScreenUpdating = True
.EnableEvents = True
End With
MsgBox ("File has been updated. DO NOT PRESS UPDATE again, as it will enter the same data once again")
End Sub
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.