VBA To Ignore Filter If Selection not found instead of Looping

nirvehex

Well-known Member
Joined
Jul 27, 2011
Messages
505
Office Version
  1. 365
Platform
  1. Windows
Hi,

I have what I think is a simple problem, but can't figure it out:

Basically, some of my sheets may have a filtered selection included, some may not, but if the selection is not found the code seems to loop forever. How do I prevent this?

Here is my code:

Code:
Worksheets("Services Export").Range("A1").AutoFilter _
  Field:=21, Criteria1:="=REC"
        
    Sheets("Services Export").Select
    Range("A1").Select
    ActiveSheet.Range(Selection, Cells(Selection.End(xlDown).Row, Selection.End(xlToRight).Column)).Select
    Selection.Copy
    Sheets("Services Export (REC)").Select
    Range("A1").Select
    Selection.PasteSpecial Paste:=xlPasteValuesAndNumberFormats, Operation:= _
        xlNone, SkipBlanks:=False, Transpose:=False

Basically, if criteria1 does not find "REC" I want the code to stop and proceed to the next piece in my code rather than loop forever and try to paste something that it can't find.

How do I add that piece in?

Thanks!
 

Excel Facts

Format cells as time
Select range and press Ctrl+Shift+2 to format cells as time. (Shift 2 is the @ sign).
Here is the whole code. Basically, I need the code to continue on to the end if it doesn't find any of the filtered selections.

Code:
Sub ServiceExportFormat()


Dim LastRow As Long
Application.ScreenUpdating = False
Sheets("Services Export").Select
Range("B2").Select
Range(Selection, Selection.End(xlDown)).Select
LastRow = Selection.Count + 1


'Create Unique Key


With Sheets("Services Export")


    .Range("A2").Formula = "=C2&""-""&N2&""-""&Z2&""-""&AA2"
    .Range("A2").AutoFill Destination:=.Range("A2:A" & LastRow)
    
End With


'Paste ServicesExport DSP


 Worksheets("Services Export").Range("A1").AutoFilter _
  Field:=21, Criteria1:="=DSP"
        
    Sheets("Services Export").Select
    Range("A1").Select
    ActiveSheet.Range(Selection, Cells(Selection.End(xlDown).Row, Selection.End(xlToRight).Column)).Select
    Selection.Copy
    Sheets("Services Export (DSP)").Select
    Range("A1").Select
    Selection.PasteSpecial Paste:=xlPasteValuesAndNumberFormats, Operation:= _
        xlNone, SkipBlanks:=False, Transpose:=False
        
'Paste ServicesExport REC
 


 Worksheets("Services Export").Range("A1").AutoFilter _
  Field:=21, Criteria1:="=REC"
        
    Sheets("Services Export").Select
    Range("A1").Select
    ActiveSheet.Range(Selection, Cells(Selection.End(xlDown).Row, Selection.End(xlToRight).Column)).Select
    Selection.Copy
    Sheets("Services Export (REC)").Select
    Range("A1").Select
    Selection.PasteSpecial Paste:=xlPasteValuesAndNumberFormats, Operation:= _
        xlNone, SkipBlanks:=False, Transpose:=False
        
'Paste ServicesExport H


 Worksheets("Services Export").Range("A1").AutoFilter _
  Field:=21, Criteria1:="=H"
        
    Sheets("Services Export").Select
    Range("A1").Select
    ActiveSheet.Range(Selection, Cells(Selection.End(xlDown).Row, Selection.End(xlToRight).Column)).Select
    Selection.Copy
    Sheets("Services Export (H)").Select
    Range("A1").Select
    Selection.PasteSpecial Paste:=xlPasteValuesAndNumberFormats, Operation:= _
        xlNone, SkipBlanks:=False, Transpose:=False
        
'Paste ServicesExport CSC


 Worksheets("Services Export").Range("A1").AutoFilter _
  Field:=21, Criteria1:="=CSC"
        
    Sheets("Services Export").Select
    Range("A1").Select
    ActiveSheet.Range(Selection, Cells(Selection.End(xlDown).Row, Selection.End(xlToRight).Column)).Select
    Selection.Copy
    Sheets("Services Export (CSC)").Select
    Range("A1").Select
    Selection.PasteSpecial Paste:=xlPasteValuesAndNumberFormats, Operation:= _
        xlNone, SkipBlanks:=False, Transpose:=False
        
'Paste ServicesExport LR


 Worksheets("Services Export").Range("A1").AutoFilter _
  Field:=21, Criteria1:="=LR"
        
    Sheets("Services Export").Select
    Range("A1").Select
    ActiveSheet.Range(Selection, Cells(Selection.End(xlDown).Row, Selection.End(xlToRight).Column)).Select
    Selection.Copy
    Sheets("Services Export (LR)").Select
    Range("A1").Select
    Selection.PasteSpecial Paste:=xlPasteValuesAndNumberFormats, Operation:= _
        xlNone, SkipBlanks:=False, Transpose:=False
        
'Paste ServicesExport MNT


 Worksheets("Services Export").Range("A1").AutoFilter _
  Field:=21, Criteria1:="=MNT"
        
    Sheets("Services Export").Select
    Range("A1").Select
    ActiveSheet.Range(Selection, Cells(Selection.End(xlDown).Row, Selection.End(xlToRight).Column)).Select
    Selection.Copy
    Sheets("Services Export (MNT)").Select
    Range("A1").Select
    Selection.PasteSpecial Paste:=xlPasteValuesAndNumberFormats, Operation:= _
        xlNone, SkipBlanks:=False, Transpose:=False
        
'Paste ServicesExport R


 Worksheets("Services Export").Range("A1").AutoFilter _
  Field:=21, Criteria1:="=R"
        
    Sheets("Services Export").Select
    Range("A1").Select
    ActiveSheet.Range(Selection, Cells(Selection.End(xlDown).Row, Selection.End(xlToRight).Column)).Select
    Selection.Copy
    Sheets("Services Export (R)").Select
    Range("A1").Select
    Selection.PasteSpecial Paste:=xlPasteValuesAndNumberFormats, Operation:= _
        xlNone, SkipBlanks:=False, Transpose:=False




End Sub
 
Upvote 0
Hi,
Try this. I've been writing this code on my mobile but there should not be aby error I suppose. Let me know if that's ok for you.

Code:
Sub CopyData()
    Dim ws_main as worksheet
    Dim ws_copyto as worksheet
    Dim no_columns&
    
    Set ws_main = activesheet.name
    Set ws_copyto=worksheets("Services Export (REC)")
     no_columns=ws_main.range("A1").currentregion.columns.count
    With ws_main
    i=2
    Do while .cells(i,"a").value=""
           If .cells(i,21).value="REC" then
               .range(.cells(i,"a"),.cells(i,no_columns).copy
               With ws_copyto 
                      .range(.cells(.range("a1").currentregion.rows.count +1,"a"),.cells(.range("a1").currentregion.rows.count +1,no_columns)).pastespecial Paste:=xlPasteValuesAndNumberFormats
                End with
           End if
           i=i+1
    Loop
   
    End with
    application.cutcopymode = false
    Set ws_main = nothing
    Set ws_copyto = nothing

[\CODE]
 
Upvote 0
Thanks Mentor82. However it's giving me an error when I compile the project on

Code:
.range(.cells(i,"a"),.cells(i,no_columns).copy

Any thoughts?

Thanks again!
 
Upvote 0
Actually I figured out on that line there was just a missing parenthesis. However, when I attempt to run the macro it gives me an error on this line if it doesn't find the selected filter value.

Code:
Do While .Cells(i, "a").Value = ""

Here is the full code:

Code:
Sub CopyData()
Dim ws_main As Worksheet
Dim ws_copyto As Worksheet
Dim no_columns&


Set ws_main = Worksheets("Services Export")
Set ws_copyto = Worksheets("Services Export (CSC)")
no_columns = ws_main.Range("A1").CurrentRegion.Columns.Count
With ws_main
i = 2
Do While .Cells(i, "a").Value = ""
If .Cells(i, 21).Value = "CSC" Then
.Range(.Cells(i, "a"), .Cells(i, no_columns)).Copy
With ws_copyto
.Range(.Cells(.Range("a1").CurrentRegion.Rows.Count + 1, "a"), .Cells(.Range("a1").CurrentRegion.Rows.Count + 1, no_columns)).PasteSpecial Paste:=xlPasteValuesAndNumberFormats
End With
End If
i = i + 1
Loop


End With
Application.CutCopyMode = False
Set ws_main = Nothing
Set ws_copyto = Nothing


End Sub

Again, if the selected value "CSC" isn't found in the filter I don't want the macro to copy or paste anything, just to end.

Thanks.
 
Upvote 0
Nevermind, figured it out.

New code:

Code:
Sub ServicesExportFormatCSC()
'Note: This macro uses the function LastRow
'Important: The DestSh must exist
    Dim My_Range As Range
    Dim DestShCSC As Worksheet
    Dim CalcMode As Long
    Dim ViewMode As Long
    Dim FilterCriteria As String
    Dim CCount As Long
    Dim rng As Range


    'Set filter range on ActiveSheet: A11 is the top left cell of your filter range
    'and the header of the first column, D is the last column in the filter range.
    'You can also add the sheet name to the code like this :
    'Worksheets("Sheet1").Range("A11:D" & LastRow(Worksheets("Sheet1")))
    'No need that the sheet is active then when you run the macro when you use this.
    Set My_Range = Worksheets("Services Export").Range("A1:CU" & LastRow(Worksheets("Services Export")))
    My_Range.Parent.Select


    'Set the destination worksheet
    Set DestShCSC = Sheets("Services Export (CSC)")


    If ActiveWorkbook.ProtectStructure = True Or _
       My_Range.Parent.ProtectContents = True Then
        MsgBox "Sorry, not working when the workbook or worksheet is protected", _
               vbOKOnly, "Copy to new worksheet"
        Exit Sub
    End If


    'Change ScreenUpdating, Calculation, EnableEvents, ....
    With Application
        CalcMode = .Calculation
        .Calculation = xlCalculationManual
        .ScreenUpdating = False
        .EnableEvents = False
    End With
    ViewMode = ActiveWindow.View
    ActiveWindow.View = xlNormalView
    ActiveSheet.DisplayPageBreaks = False


    'Firstly, remove the AutoFilter
    My_Range.Parent.AutoFilterMode = False


    'Filter and set the filter field and the filter criteria :
    'This example filter on the first column in the range (change the field if needed)
    'In this case the range starts in A so Field 1 is column A, 2 = column B, ......
    My_Range.AutoFilter Field:=21, Criteria1:="=CSC"


    'If you want to filter on a cell value you can use this, use "<>" for the opposite
    'This example uses the activecell value
    'My_Range.AutoFilter Field:=1, Criteria1:="=" & ActiveCell.Value


    'This will use the cell value from A2 as criteria
    'My_Range.AutoFilter Field:=1, Criteria1:="=" & Range("A2").Value


    ''If you want to filter on a Inputbox value use this
    'FilterCriteria = InputBox("What text do you want to filter on?", _
     '                          "Enter the filter item.")
    'My_Range.AutoFilter Field:=1, Criteria1:="=" & FilterCriteria




    'Check if there are not more then 8192 areas(limit of areas that Excel can copy)
    CCount = 0
    On Error Resume Next
    CCount = My_Range.Columns(1).SpecialCells(xlCellTypeVisible).Areas(1).Cells.Count
    On Error GoTo 0
    If CCount = 0 Then
        MsgBox "There are more than 8192 areas:" _
             & vbNewLine & "It is not possible to copy the visible data." _
             & vbNewLine & "Tip: Sort your data before you use this macro.", _
               vbOKOnly, "Copy to worksheet"
    Else
        'Copy the visible data and use PasteSpecial to paste to the Destsh
        With My_Range.Parent.AutoFilter.Range
            On Error Resume Next
            ' Set rng to the visible cells in My_Range without the header row
            Set rng = .Offset(0, 0).Resize(.Rows.Count, .Columns.Count) _
                      .SpecialCells(xlCellTypeVisible)
            On Error GoTo 0
            If Not rng Is Nothing Then
                'Copy and paste the cells into DestSh below the existing data
                rng.Copy
                With DestShCSC.Range("A" & LastRow(DestShCSC) + 1)
                    ' Paste:=8 will copy the columnwidth in Excel 2000 and higher
                    ' Remove this line if you use Excel 97
                    .PasteSpecial Paste:=8
                    .PasteSpecial xlPasteValues
                    .PasteSpecial xlPasteFormats
                    Application.CutCopyMode = False
                End With
                'Delete the rows in the My_Range.Parent worksheet
                'rng.EntireRow.Delete
            End If
        End With
    End If


    'Close AutoFilter
    My_Range.Parent.AutoFilterMode = False


    'Restore ScreenUpdating, Calculation, EnableEvents, ....
    ActiveWindow.View = ViewMode
    Application.Goto DestShCSC.Range("A1")
    With Application
        .ScreenUpdating = True
        .EnableEvents = True
        .Calculation = CalcMode
    End With


End Sub
 
Upvote 0

Forum statistics

Threads
1,224,820
Messages
6,181,160
Members
453,021
Latest member
Justyna P

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top