![](/img/trans.png)
[英]VBA Runtime Error 1004 “Application-defined or Object-defined error” when trying to assign value to a variable
[英]I keep getting a 1004 Error Application-Defined or Object-Defined Error when trying to copy and paste
我正在嘗試從工作表“ AgentName”中將范圍A:3復制到A:x(其中x是表“ AgentName”中的行數),但是,每當我嘗試復制包含變量的范圍時,它給我錯誤1004。我已經閱讀了所有可以找到的內容。 這是我嘗試過的兩個常見問題。
Worksheets("AgentName").Range("A3:A"&x).copy
Worksheets("AgentName").Range(Sheets("AgentName").Cells(3, 1), Sheets("AgentName").Cells(x, 1)).Copy
^我嘗試了沒有表格,僅包含單元格,包含單元格和范圍的表格。
這是代碼的簡化版:
Private Sub CommandButton1_Click()
'CountRows in AgentName Table
Dim myWorkSheet As Worksheet, myTable As ListObject, x As Long
Set myWorkSheet = ActiveWorkbook.Worksheets("AgentName")
Set myTable = myWorkSheet.ListObjects("AgentName")
x = myTable.DataBodyRange.Rows.Count
'Specific Forms for All Agents (Motivated)
If Range("B3").Value = "All Agents" And Range("C3").Value = "Motivated" Then
Worksheets("Other Forms").Range("A1:H2").Copy
Worksheets("Master").Range("B6:I7").PasteSpecial
Worksheets("AgentName").Range(Sheets("AgentName").Cells(3, 1), Sheets("AgentName").Cells(x, 1)).Copy
Worksheets("Master").Range("B8:B13").PasteSpecial
Range("B6:I13").Borders.LineStyle = xlContinuous
End If
End Sub
我看到兩個潛在的錯誤源:首先,將非恆定大小的范圍復制並粘貼到具有恆定大小的范圍內,即:
Worksheets("AgentName").Range(Sheets("AgentName").Cells(3, 1), Sheets("AgentName").Cells(x, 1)).Copy
Worksheets("Master").Range("B8:B13").PasteSpecial
如果x不等於8,則將A3:Ax粘貼到B8:B13中,這將給您帶來錯誤,因此只需將其粘貼到第一個單元格中,excel就會假定您將要粘貼其余的內容。 因此:
Worksheets("Master").Range("B8").PasteSpecial
代替。
第二點是復制的結構:
Worksheets("AgentName").Range(Sheets("AgentName").Cells(3, 1), Sheets("AgentName").Cells(x, 1)).Copy
如果您已經定義了listobject,我寧願使用listobject。
mytable.databodyrange(1,mytable.listrows.count).copy
這或非常相似的東西應該起作用。 請注意,.row為您提供了絕對行,listrow為您提供了相對於表的行。 因此,無論表是什么, mytable.databodyrange(1,3)
都將是表的第一行和第三列中的條目。 這可以是絕對行9053和絕對列456。通常最好使用這樣的相對坐標,您將能夠再次將代碼用於其他目的,並且只需要調整表格即可。
祝您好運,希望對您有所幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.