问题
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