I am seeing the runtime error message “1004” [duplicate]

倾然丶 夕夏残阳落幕 提交于 2019-12-23 07:05:10

问题


I am seeing "Run-time Error 1004" at lastrow = Sheet1.Cells(Rows.Count, 1).End(x1Up).Row in my code:

Sub copycolumns()
Dim lastrow As Long, erow As Long
lastrow = Sheet1.Cells(Rows.Count, 1).End(x1Up).Row
For i = 2 To lastrow
If Sheet1.Cells(i, 6) = "Algiers" Then
Sheet1.Cells(i, 1).Copy
erow = Sheet2.Cells(Rows.Count, 1).End(x1Up).Offset(1, 0).Row
Sheet1.Paste Destination:=Worksheets("Sheet2").Cells(erow, 1)
Sheet1.Cells(i, 3).Copy
Sheet1.Paste Destination:=Worksheets("Sheet2").Cells(erow, 2)
Sheet1.Cells(i, 6).Copy
Sheet1.Paste Destination:=Worksheets("Sheet2").Cells(erow, 3)
End If
Next i
Application.CutCopyMode = False
Sheet2.Columns().AutoFit
Range("A1").Select
End Sub

Can you help?


回答1:


You need a worksheet object, and xlUp is not equal to x1Up(your code has a typo i.e. digit 1).

use below line

lastrow = ThisWorkbook.Worksheets("sheet1").Cells(Rows.Count, 1).End(xlUp).Row

instead of

lastrow = Sheet1.Cells(Rows.Count, 1).End(x1Up).Row

Full code

Sub RoundedRectangle2_Click()
Dim lastrow, erow As Long
lastrow = ThisWorkbook.Worksheets("sheet1").Cells(Rows.Count, 1).End(xlUp).Row
For i = 2 To lastrow
If Sheet1.Cells(i, 6) = "Algiers" Then
Sheet1.Cells(i, 1).Copy

erow = ThisWorkbook.Worksheets("sheet2").Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
Sheet1.Paste Destination:=Worksheets("Sheet2").Cells(erow, 1)
Sheet1.Cells(i, 3).Copy
Sheet1.Paste Destination:=Worksheets("Sheet2").Cells(erow, 2)
Sheet1.Cells(i, 6).Copy
Sheet1.Paste Destination:=Worksheets("Sheet2").Cells(erow, 3)
End If
Next i
Application.CutCopyMode = False
Sheet2.Columns().AutoFit
Range("A1").Select
End Sub

Alternatively, you can use below line to find the rows count

rows_count = WorksheetFunction.CountA(ThisWorkbook.Worksheets("Sheet1").Range("A:A"))


来源:https://stackoverflow.com/questions/35513779/i-am-seeing-the-runtime-error-message-1004

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!