我遇到错误
运行时错误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