VBA to Copy Rows to Another Worksheet Based on Criteria

MrsTeach

New Member
Joined
Jan 4, 2023
Messages
6
Office Version
  1. 365
Platform
  1. Web
I'd really appreciate help with the following please?

I have a list where the user selects a Local Authority which then triggers a macro. I need the macro to copy all matching rows on another worksheet to a new worksheet so that the worksheet only contains data for the Local Authority.

I have the drop-down list and a macro button and can create the new worksheet but I'd like an optimal solution for matching against the other worksheet as it has approx 10k rows.

The user selects a Local Authority (from a drop-down box on the first sheet), which then needs to be matched to a LA code (on another sheet) then copy all matching entries to a new worksheet.

Book1.xlsx
ABCDEF
1LA CodeLA NAME
21Norfolk, Suffolk and Cambridgeshire
32Bedforshire & Hertfordshire
43Essex
54North West London
65North Central London
76North East London
87South East London
98South West London
109Northumberland, Tyne & Wear
1110County Durham and Tees Valley
1211North and East Yorkshire and Northern Lincolnshire
1312West Yorkshire
1413Cumbria and Lancashire
1514Greater Manchester
1615Cheshire and Merseyside
1716Thames Valley
1817Hampshire and Isle of Wight
1918Kent and Medway
2019Surrey and Sussex
2120Avon, Gloucestershire and Wiltshire
2221South West Peninsula
2322Dorset and Somerset
2423South Yorkshire
2524Trent
2625Leicestershire, Northamptonshire and Rutland
2726Shropshire and Staffordshire
2827Birmingham and the Black Country
2928Coventry, Warwickshire, Herefordshire and Worcestershire
30
Index


For example. If the user selected "Norfolk, Suffolk and Cambridgeshire" on Sheet 1, I need to find the matching LA code on the 'Index' worksheet and copy all rows for that Authority on the 'Data' worksheet to a new Sheet 3 (which needs to be given the name of the selected Local Authority: e.g.Norfolk, Suffolk and Cambridgeshire)

Book1.xlsx
ABCDEFG
1schoolnrclassHealth Authsexage
2101051112017
3101151112018
4101201112023
5101271122019
6101271222024
7101351132025
8101351232025
9101351332026
10101371122017
11101371222028
12102051121115
13102051221124
14102201121126
15102201221117
16102251141125
17102251241118
18102251341129
19102251441116
20102271131126
21102271231118
22102271331127
23102341111129
24102351111124
25103051112625
26103181122615
27103181222624
28103201112626
291033711126210
30
Data


Hope that makes sense and anyone can help! Thanks in advance.
 

Excel Facts

How to fill five years of quarters?
Type 1Q-2023 in a cell. Grab the fill handle and drag down or right. After 4Q-2023, Excel will jump to 1Q-2024. Dash can be any character.
Hi @MrsTeach , happy new year!

You didn't mention a few things:
- The name of the first sheet.
- In which cell of the first sheet do you have the drop-down list
- The name of the destination sheet.
- In which column of the Data sheet should the LA Code be searched?

But don't worry, you can adjust that data in the macro.
I added some comments in the macro for you to make those adjustments. They are marked in blue in the code.

Try this:


Rich (BB code):
Sub CopyRows()
  Dim sh1 As Worksheet, sh3 As Worksheet, shI As Worksheet, shD As Worksheet
  Dim f As Range, cellName As Range
  Dim LaCode As Variant
  Dim a As Variant, b As Variant
  Dim i As Long, j As Long, k As Long
 
  'Fit to the name of your sheets
  Set sh1 = Sheets("Sheet1")  'first sheet
  Set sh3 = Sheets("Sheet3")  'New sheet
  Set shI = Sheets("Index")   'Index sheet
  Set shD = Sheets("Data")    'Data sheet
 
  Set cellName = sh1.Range("B2")  'Fit to the cell with drop-down box on the first sheet
 
  If cellName.Value = "" Then
    MsgBox "Select name"
    Exit Sub
  End If
 
  'Look up the name in the Index sheet and get the LA code
  Set f = shI.Range("B:B").Find(cellName.Value, , xlValues, xlWhole, , , False)
  If f Is Nothing Then
    MsgBox "That name does not exist"
    Exit Sub
  Else
    LaCode = shI.Range("A" & f.Row).Value
  End If
 
  a = shD.Range("A2:F" & shD.Range("A" & Rows.Count).End(3).Row).Value
  ReDim b(1 To UBound(a, 1), 1 To UBound(a, 2))
 
  For i = 1 To UBound(a, 1)
    'fit the column number to search for the LaCode, 1 for "A", 2 for "B", 3 for "C", etc.
    If a(i, 2) = LaCode Then
      k = k + 1
      For j = 1 To UBound(a, 2)
        b(k, j) = a(i, j)
      Next
    End If
  Next
 
  sh3.Cells.ClearContents
  shD.Rows(1).Copy sh3.Range("A1")
  If k = 0 Then
    MsgBox "No records"
  Else
    sh3.Range("A2").Resize(k, UBound(b, 2)).Value = b
  End If
End Sub
 
Upvote 0
Hi,

using Advanced Filter setting sheets up like

MrE_1226120_170051C_vba to copy rows to_230105.xlsm
ABCDEFG
1LA CodeLA NAMEChooseLocal AuthorityNorth and East Yorkshire and Northern LincolnshireHealth Auth
21Norfolk, Suffolk and Cambridgeshire11
32Bedforshire & Hertfordshire
43Essex
54North West London
65North Central London
76North East London
87South East London
98South West London
109Northumberland, Tyne & Wear
1110County Durham and Tees Valley
1211North and East Yorkshire and Northern Lincolnshire
1312West Yorkshire
1413Cumbria and Lancashire
1514Greater Manchester
1615Cheshire and Merseyside
1716Thames Valley
1817Hampshire and Isle of Wight
1918Kent and Medway
2019Surrey and Sussex
2120Avon, Gloucestershire and Wiltshire
2221South West Peninsula
2322Dorset and Somerset
2423South Yorkshire
2524Trent
2625Leicestershire, Northamptonshire and Rutland
2726Shropshire and Staffordshire
2827Birmingham and the Black Country
2928Coventry, Warwickshire, Herefordshire and Worcestershire
Index
Cell Formulas
RangeFormula
G2G2=IFERROR(INDEX(A:A,MATCH(E1,B:B,0)),"")
Named Ranges
NameRefers ToCells
_FilterDatabase=Index!$A$1:$F$29G2
PickList=Index!$B$2:$B$29G2
Cells with Data Validation
CellAllowCriteria
E1List=PickList


MrE_1226120_170051C_vba to copy rows to_230105.xlsm
ABCDEF
1schoolnrclassHealth Authsexage
2101051112017
3101151112018
4101201112023
5101271122019
6101271222024
7101351132025
8101351232025
9101351332026
10101371122017
11101371222028
12102051121115
13102051221124
14102201121126
15102201221117
16102251141125
17102251241118
18102251341129
19102251441116
20102271131126
21102271231118
22102271331127
23102341111129
24102351111124
25103051112625
26103181122615
27103181222624
28103201112626
291033711126210
Data


Code goes behind sheet Index and will be triggered each time a value is chosen in E1:

VBA Code:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim wsNew As Worksheet
If Target.Count > 1 Then Exit Sub
If Not Intersect(Target, Range("E1")) Is Nothing Then
  If WorksheetFunction.CountIf(Sheets("Data").Columns(4), Worksheets("Index").Range("G2").Value) > 0 Then
    If Not Evaluate("ISREF('" & Left(Range("E1").Value, 31) & "'!A1)") Then
      Set wsNew = Worksheets.Add(After:=Worksheets(ThisWorkbook.Worksheets.Count))
      wsNew.Name = Left(Sheets("Index").Range("E1").Value, 31)
    Else
      Set wsNew = Worksheets(Left(Sheets("Index").Range("E1").Value, 31))
      wsNew.Cells.ClearContents
    End If
    Sheets("Data").Range("A1:F" & Sheets("data").Cells(Rows.Count, "A").End(xlUp).Row).AdvancedFilter Action:=xlFilterCopy, _
        CriteriaRange:=Sheets("Index").Range("G1:G2"), _
        CopyToRange:=wsNew.Range("A5:F5"), _
        Unique:=False
  End If
End If
Set wsNew = Nothing
End Sub

Ciao,
Holger
 
Upvote 0

Forum statistics

Threads
1,224,824
Messages
6,181,186
Members
453,020
Latest member
Mohamed Magdi Tawfiq Emam

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