vba

indesisiv

Access - What's that?
Local time
Today, 18:34
Joined
Jun 13, 2002
Messages
265
Hi,

I am trying to get exel to copy data from several worksheets and place the data in another sheet.
In this case there are 2 parts. I want to copy data from all of the sheets that begin with stdy based on the following
I want to copy the data in cells A:H based on the value in cell G and
cells J-P based on cell O.

For example it needs to loop round all the sheets, if the value in row G = "core" then cells A:H need copying in the "core" sheet in the next available cells A:H.

THis is in Excel 2010. I know that i will need to do this as a module because i can't seem to think of any other way to do it. It has been a while since i have done any vba and certainly not for a very long time in Excel.

Can anybody help?
 

Attachments

I have found an example and modified that a bit.
I have it working for a single button on an active sheet for 1 column of the data but it shouldn't be to hard to get the other section of the data.

Can anyone help with putting this code onto any other sheet so that it loops round all the worksheets with stdy ... as their name and copies to the next available line on the core sheet?

Code:
Sub Copy_With_AutoFilter2()
'Note: This macro use the function LastRow
'Important: The DestSh must exist
    Dim My_Range As Range
    Dim DestSh 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 = Range("A2:G" & LastRow(ActiveSheet))
    My_Range.Parent.Select

    'Set the destination worksheet
    'Note: the sheet "RecordsOfTheNetherlands" must exist in your workbook.
    Set DestSh = Sheets("Core")

    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, ......
    'Use "<>Netherlands" as criteria if you want the opposite
    My_Range.AutoFilter Field:=7, Criteria1:="=Core"

    '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(1, 0).Resize(.Rows.Count - 1, .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 DestSh.Range("A" & LastRow(DestSh) + 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 DestSh.Range("A2")
    With Application
        .ScreenUpdating = True
        .EnableEvents = True
        .Calculation = CalcMode
    End With

End Sub

Code:
Function LastRow(sh As Worksheet)
    On Error Resume Next
    LastRow = sh.Cells.Find(What:="*", _
                            After:=sh.Range("A1"), _
                            Lookat:=xlPart, _
                            LookIn:=xlValues, _
                            SearchOrder:=xlByRows, _
                            SearchDirection:=xlPrevious, _
                            MatchCase:=False).Row
    On Error GoTo 0
End Function
 
Move the code to ThisWorkbook, then add the statements in red is a simple way to do this. I have assumed that the stdy sheets will appear first in the workbook

Brian

Code:
Sub Copy_With_AutoFilter2()
'Note: This macro use the function LastRow
'Important: The DestSh must exist
    Dim My_Range As Range
    Dim DestSh As Worksheet
    [COLOR="Red"]Dim sourcesht As Worksheet[/COLOR] 
    Dim CalcMode As Long
    Dim ViewMode As Long
    Dim FilterCriteria As String
    Dim CCount As Long
    Dim rng As Range
    [COLOR="red"]Dim n As Integer[/COLOR]
    '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.
    [COLOR="red"]n = 0
    Do While n < 2
    n = n + 1
    Set sourcesht = Sheets(n)
    sourcesht.Activate[/COLOR]
    Set My_Range = Range("A2:G" & LastRow(ActiveSheet))
    My_Range.Parent.Select

    'Set the destination worksheet
    'Note: the sheet "RecordsOfTheNetherlands" must exist in your workbook.
    Set DestSh = Sheets("Core")

    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, ......
    'Use "<>Netherlands" as criteria if you want the opposite
    My_Range.AutoFilter Field:=7, Criteria1:="=Core"

    '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(1, 0).Resize(.Rows.Count - 1, .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 DestSh.Range("A" & LastRow(DestSh) + 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
    [COLOR="red"]Loop[/COLOR]    

    'Close AutoFilter
    My_Range.Parent.AutoFilterMode = False

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

End Sub
 
Oh BTW forgot to mention on testing noticed that the first row of data missing, your range should include the header row as per the comments.

Brian
 
Thanks for this i will see if I can sort it out.
I have deliberatly taken out the header rows, I will find a way to clear the destination sheet or copy one header across. As it is going to pull data from about 20 sheets i didn't want to confuse the copy to just take one header.
 
I am confused by your response.
As your code stood the first row of of data below the header row is missing.

The function assumes a header row on source sheet and starts the copy below it so by saying your range starts in row 2 it omits that row.

Brian
 
That makes sense now. I didn't have data that matched in the first row so i didn't notice that it was missing it out.
 

Users who are viewing this thread

Back
Top Bottom