I have an autofiltered table in Excel. I have to copy/paste values based on certain conditions and I also have to perform this on all visible cells in a particular column. I have written the code and it works well but the only thing is that it takes a lot of time as there are many rows. Can anyone please help me how to thrash time required? Here's the code. Thanks!
Sub FilterAndCopy()
Windows("Epson Itemcodes.xlsm").Activate
Range("A" & i).Select
Selection.Copy
Windows("Epson ASINs.xlsx").Activate
Range("U1048576").End(xlUp).Offset(0, -12).Select
If ActiveCell.Value <> "Itemcode" Then
If ActiveCell.Value = "" Then
ActiveSheet.Paste
Else
If ActiveCell.Value = Workbooks("Epson Itemcodes.xlsm").Sheets("Sheet1").Range("A" & i).Value Then
ActiveSheet.Paste
Else
ActiveCell.Value = "Conflct"
End If
End If
Else
Windows("Epson Itemcodes.xlsm").Activate
Range("I" & i).Value = "No match found"
End If
If ActiveCell.Value <> "Itemcode" Then
With ActiveSheet
Do
ActiveCell.Offset(-1, 0).Activate
Do While ActiveCell.EntireRow.Hidden = True
ActiveCell.Offset(-1, 0).Activate
Loop
If ActiveCell.Value <> "Itemcode" Then
If ActiveCell.Value = "" Then
ActiveSheet.Paste
Else
If ActiveCell.Value = Workbooks("Epson Itemcodes.xlsm").Sheets("Sheet1").Range("A" & i).Value Then
ActiveSheet.Paste
Else
ActiveCell.Value = "Conflct"
End If
End If
Else
Exit Do
End If
Loop
End With
End If
End Sub
1 Answer 1
Before you write another line of code, watch this Excel VBA Introduction Part 5 - Selecting Cells (Range, Cells, Activecell, End, Offset).
Everyone here wants to help you but, and I know that you read this, you have got to stop selecting and activating cells. You also need to describe your data. Posting screenshots wouldn't hurt either. So if I sound mean but you wrote 72 lines of code to copy maybe 12 values.
Range.Copy
, Range.Cut
, Range.Insert
and by default act on only the visible cells.
Sub FilterAndCopy()
Dim Source As Range, Target As Range
With Workbooks("Epson ASINs.xlsx").Worksheets("Sheet1")
Set Source = .Range("U2", .Range("U" & .Rows.Count).End(xlUp)).SpecialCells(xlCellTypeVisible)
End With
With Workbooks("Epson Itemcodes.xlsm").Worksheets("Sheet1")
Set Target = .Range("U" & .Rows.Count).End(xlUp).Offset(1)
End With
Source.Offset(1).Copy Desination:=Target
End Sub
i
is never set and the first statement would fail.) This site is for reviewing working code. You can find some extremely helpful tips on using Option Explicit, avoiding SELECT, with other very useful tips. \$\endgroup\$