Search code examples
excelvbafiltercopy-paste

Method Range of Object_Worksheet i can only make the first or 2nd part work


Sorry for my English.

I have a problem with a code where I get information from different sheets to one sheet. With slicer i'm able to only get the necessary information. All worked well till I needed to get a sorting on the data before i copied it. People where using the sheets and filtered and did all sort of things to the list. While I'm writing this I'm thinking maybe i can split it in two because it worked fine before so why not just a code for filtering.. Still I would like to know the solution in my code because I just don't get why it wont work. The problem is (now) in the 2nd part of the code after 'copy paste.

all named references are checked and correct (it worked fine before the filter part) but somehow in the filter part it does something so the code for copy paste wont work.

Option Explicit

Sub GetDataForSlicersSel()
Dim wsAF As Worksheet
Dim wsEM As Worksheet
Dim wsEI As Worksheet
Dim wsOP As Worksheet
Dim wsPG As Worksheet
Dim wsRK As Worksheet
Dim wsKM As Worksheet
Dim wsBK As Worksheet
Dim wsVE As Worksheet
Dim wsRE As Worksheet
Dim wsCP As Worksheet

Set wsAF = Sheets("afblijven")
Set wsEM = Sheets("1721 Energiemeters")
Set wsEI = Sheets("2704 E-installatie OA")
Set wsOP = Sheets("output")
Set wsPG = Sheets("Projectgegevens")
Set wsRK = Sheets("2601 Regelkast-OVK")
Set wsKM = Sheets("2611 Klein Materiaal")
Set wsBK = Sheets("2614 Bekabeling OA")
Set wsVE = Sheets("2621 Veldapparatuur")
Set wsRE = Sheets("2634 Regelinstallatie OA")
Set wsCP = Sheets("1711 Circulatiepompen")

Application.ScreenUpdating = False

'filter
wsEM.Select
wsEM.Sort.SortFields.Clear
Range("EMtabel").Sort key1:=Range("a2"), Header:=xlYes
ActiveSheet.Sort.SortFields.Clear
wsOP.Select

'copy paste
wsEM.Range("EMtabel[#All]").AdvancedFilter _
 Action:=xlFilterCopy, _
 CriteriaRange:=wsAF.Range("Critslicers"), _
 CopyToRange:=wsOP.Range("ExtractSlicersEM"), _
 Unique:=False

Application.ScreenUpdating = True


End Sub

Solution

  • Solved because of a stupid mistake from my part. This code won't work with F5 or F8 in VBA but will work on a button. Thanks to the advice i also rewritten the code a bit. The code now (i still have the dim and set part but for the lenght of the post i excluded this):

        'filter
    With wsEI.Sort
    .SortFields.Add Key:=Range("a2"), Order:=xlAscending
    .SetRange Range("E_installaties")
    .Header = xlYes
    .Apply
    End With
    
    'copy paste
    With wsEI
    .Range("E_installaties[#All]").AdvancedFilter _
      Action:=xlFilterCopy, _
      CriteriaRange:=wsAF.Range("Critslicers"), _
      CopyToRange:=wsOP.Range("ExtractSlicersEI"), _
      Unique:=False
    End With
    

    Thanks all for helping!