I'm running the below code and getting Next without For , I'm I missing something. I want to retain the four excel sheets which comes first namely
1. Sheet1
2. InvoicesConsolidated
3. Merge_Excel
4. Consolidated
Rest of the sheets were imported into excel and need to be consolidated into sheet name "Consolidated" and get deleted after consolidation. I try to include the sheets names which I don't want to delete and added end if results in error while executing.
Code1: (this code checks invoices in A range of sheet1 with invoices range in "invoicesconsolidated" by filtering the K column and copying the filtered items into new sheet with sheet named with invoice number
Sub filter()
Application.ScreenUpdating = False
Dim x As Range
Dim rng As Range
Dim Last As Long
Dim sht As String
Dim shtb As String
sht = "InvoicesConsolidated"
shtb = "Sheet1"
'change filter column in the following code
Last = Sheets(sht).Cells(Rows.Count, "K").End(xlUp).Row
Set rng = Sheets(sht).Range("A1:K" & Last)
'Sheets(shtb).Range("A1:A" & last).AdvancedFilter Action:=xlFilterCopy, CopyToRange:=Range("AA1"), Unique:=True
For Each x In shtb.Range([A2], Cells(Rows.Count, "A").End(xlUp))
With rng
.AutoFilter
.AutoFilter Field:=11, Criteria1:=x.Value
.SpecialCells(xlCellTypeVisible).Copy
Sheets.Add(After:=Sheets(Sheets.Count)).Name = x.Value
ActiveSheet.Paste
End With
Next x
'Turn off filter
Sheets(sht).AutoFilterMode = False
With Application
.CutCopyMode = False
.ScreenUpdating = True
End With
Sheets("InvoicesConsolidated").Select
End Sub
Code 2: (this code actually, consolidates the sheets which created after matching invoices into one single sheet and deleting the rest of the sheets.
Private Sub CommandButton2_Click()
Dim sh As Worksheet
Dim DestSh As Worksheet
Dim Last As Long
Dim shLast As Long
Dim CopyRng As Range
Dim StartRow As Long
With Application
.ScreenUpdating = False
.EnableEvents = False
End With
' Delete the summary sheet if it exists.
Application.DisplayAlerts = False
On Error Resume Next
ActiveWorkbook.Worksheets("Consolidated").Delete
On Error GoTo 0
Application.DisplayAlerts = False
' Add a new summary worksheet.
Set DestSh = ActiveWorkbook.Worksheets.Add
DestSh.Name = "Consolidated"
' Fill in the start row.
StartRow = 1
' Loop through all worksheets and copy the data to the
' summary worksheet.
For Each sh In ActiveWorkbook.Worksheets
If sh.Name <> DestSh.Name Then
If sh.Name <> "Merge_Excel" Then
If sh.Name <> "Sheet1" Then
If sh.Name <> "InvoicesConsolidated" Then
' Find the last row with data on the summary
' and source worksheets.
Last = LastRow(DestSh)
shLast = LastRow(sh)
' If source worksheet is not empty and if the last
' row >= StartRow, copy the range.
If shLast > 0 And shLast >= StartRow Then
'Set the range that you want to copy
Set CopyRng = sh.Range(sh.Rows(StartRow), sh.Rows(shLast))
' Test to see whether there are enough rows in the summary
' worksheet to copy all the data.
If Last + CopyRng.Rows.Count > DestSh.Rows.Count Then
MsgBox "There are not enough rows in the " & _
"summary worksheet to place the data."
GoTo ExitTheSub
End If
End If
End If
StartRow = 1
' This statement copies values and formats.
CopyRng.Copy
With DestSh.Cells(Last + 1, "A")
.PasteSpecial xlPasteValues
.PasteSpecial xlPasteFormats
Application.CutCopyMode = False
End With
End If
End If
End If
Application.DisplayAlerts = False
If sh.Name <> "Merge_Excel" Then
If sh.Name <> "Sheet1" Then
If sh.Name <> "InvoicesConsolidated" Then
On Error Resume Next
If sh.Name <> "Consolidated" Then ActiveWorkbook.Worksheets(sh.Name).Delete
On Error GoTo 0
Application.DisplayAlerts = True
End If
Next
ExitTheSub:
' AutoFit the column width in the summary sheet.
DestSh.Columns.AutoFit
'ThisWorkbook.Sheets("Consolidated").Range("A1:K50000").Sort Key1:=ThisWorkbook.Sheets("Consolidated").Range("A2"), Order1:=xlDescending, Header:=xlYes
ReadOutlineCells
With Application
.ScreenUpdating = True
.EnableEvents = True
End With
MsgBox ("Consolidated")
End Sub
Function LastRow(sh As Worksheet)
On Error Resume Next
LastRow = sh.Cells.Find(What:="*", _
After:=sh.Range("A1"), _
Lookat:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row
On Error GoTo 0
End Function
Function LastCol(sh As Worksheet)
On Error Resume Next
LastCol = sh.Cells.Find(What:="*", _
After:=sh.Range("A1"), _
Lookat:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByColumns, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Column
On Error GoTo 0
End Function
Function ReadOutlineCells()
Dim rng As Range
Set rng = ActiveWorkbook.Worksheets("Consolidated").Range("A1:K10000")
With rng.Borders
.LineStyle = xlContinuous
.Color = vbBlack
End With
End Function'
Your multiple criteria of If <> ... in the section below:
If sh.Name <> DestSh.Name Then
If sh.Name <> "Merge_Excel" Then
If sh.Name <> "Sheet1" Then
If sh.Name <> "InvoicesConsolidated" Then
Could be easily replaced with a Select Case like in the code below:
Select Case sh.Name
Case DestSh.Name, "Merge_Excel", "Sheet1", "InvoicesConsolidated"
' do nothing
Case Else
' this is the scenario you are describing in your code
' rest of your code goes here
End Select
If you correct your indentations, you'll find the problem much quicker.
I have made an attempt at it below and that led to some added rows and some deleted ones. I'm not sure if that is the logic you sought, but the message here is to keep your indentation in good shape at all times - especially while writing the code.
Private Sub CommandButton2_Click()
Dim sh As Worksheet
Dim DestSh As Worksheet
Dim Last As Long
Dim shLast As Long
Dim CopyRng As Range
Dim StartRow As Long
With Application
.ScreenUpdating = False
.EnableEvents = False
End With
' Delete the summary sheet if it exists.
Application.DisplayAlerts = False
On Error Resume Next
ActiveWorkbook.Worksheets("Consolidated").Delete
On Error GoTo 0
Application.DisplayAlerts = False
' Add a new summary worksheet.
Set DestSh = ActiveWorkbook.Worksheets.Add
DestSh.Name = "Consolidated"
' Fill in the start row.
StartRow = 1
' Loop through all worksheets and copy the data to the
' summary worksheet.
For Each sh In ActiveWorkbook.Worksheets
If sh.Name <> DestSh.Name Then
If sh.Name <> "Merge_Excel" Then
If sh.Name <> "Sheet1" Then
If sh.Name <> "InvoicesConsolidated" Then
' Find the last row with data on the summary
' and source worksheets.
Last = LastRow(DestSh)
shLast = LastRow(sh)
' If source worksheet is not empty and if the last
' row >= StartRow, copy the range.
If shLast > 0 And shLast >= StartRow Then
'Set the range that you want to copy
Set CopyRng = sh.Range(sh.Rows(StartRow), sh.Rows(shLast))
' Test to see whether there are enough rows in the summary
' worksheet to copy all the data.
If Last + CopyRng.Rows.Count > DestSh.Rows.Count Then
MsgBox "There are not enough rows in the " & _
"summary worksheet to place the data."
GoTo ExitTheSub
End If
End If
End If
End If
StartRow = 1
' This statement copies values and formats.
CopyRng.Copy
With DestSh.Cells(Last + 1, "A")
.PasteSpecial xlPasteValues
.PasteSpecial xlPasteFormats
Application.CutCopyMode = False
End With
End If
End If
Application.DisplayAlerts = False
If sh.Name <> "Merge_Excel" Then
If sh.Name <> "Sheet1" Then
If sh.Name <> "InvoicesConsolidated" Then
On Error Resume Next
If sh.Name <> "Consolidated" Then ActiveWorkbook.Worksheets(sh.Name).Delete
On Error GoTo 0
Application.DisplayAlerts = True
End If
End If
End If
Next
ExitTheSub:
' AutoFit the column width in the summary sheet.
DestSh.Columns.AutoFit
'ThisWorkbook.Sheets("Consolidated").Range("A1:K50000").Sort Key1:=ThisWorkbook.Sheets("Consolidated").Range("A2"), Order1:=xlDescending, Header:=xlYes
ReadOutlineCells
With Application
.ScreenUpdating = True
.EnableEvents = True
End With
MsgBox ("Consolidated")
End Sub
Related
I have multiple sheets, each with data only in the first two columns:
Column A - ID
Column B - Name
I am trying to consolidate all these sheets into a master sheet. The format of the master sheet should be:
Column A - Sheet Name (From where the data was copied)
Column B - ID
Column C - Name
I have found a site that has code that does more or less this, however, after messing around with it for what feels like an eternity I just cannot get it to work.
The code works, in the sense that it copies the correct range and inputs the sheet name into column A, however, it doesn't stop by the "last row" of the range in the master sheet, it continues to populate the ENTIRE column A and the IF Statement that counts the rows is triggered and I get the msgbox pop up (see below in code). At this point, the code just ends and it does not get a chance to execute for the remaining sheets.
Link to site: https://www.rondebruin.nl/win/s3/win002.htm
Below is the code from the original site, with some minor adjustments for the range I will be using:
Sub CopySheetNameToColumn()
Dim sh As Worksheet
Dim DestSh As Worksheet
Dim Last As Long
Dim CopyRng As Range
With Application
.ScreenUpdating = False
.EnableEvents = False
End With
'Delete the sheet "RDBMergeSheet" if it exist
Application.DisplayAlerts = False
On Error Resume Next
ActiveWorkbook.Worksheets("RDBMergeSheet").Delete
On Error GoTo 0
Application.DisplayAlerts = True
'Add a worksheet with the name "RDBMergeSheet"
Set DestSh = ActiveWorkbook.Worksheets.Add
DestSh.Name = "RDBMergeSheet"
'loop through all worksheets and copy the data to the DestSh
For Each sh In ActiveWorkbook.Worksheets
If sh.Name <> DestSh.Name Then
'Find the last row with data on the DestSh
Last = LastRow(DestSh)
'Fill in the range that you want to copy
Set CopyRng = sh.Range("A:B")
'Test if there enough rows in the DestSh to copy all the data
If Last + CopyRng.Rows.count > DestSh.Rows.count Then
MsgBox "There are not enough rows in the Destsh"
GoTo ExitTheSub
End If
'This example copies values/formats, if you only want to copy the
'values or want to copy everything look at the example below this macro
CopyRng.Copy
With DestSh.Cells(Last + 1, "B")
.PasteSpecial xlPasteValues
.PasteSpecial xlPasteFormats
Application.CutCopyMode = False
End With
'Optional: This will copy the sheet name in the H column
DestSh.Cells(Last + 1, "A").Resize(CopyRng.Rows.count).Value = sh.Name
End If
Next
ExitTheSub:
Application.Goto DestSh.Cells(1)
'AutoFit the column width in the DestSh sheet
DestSh.Columns.AutoFit
With Application
.ScreenUpdating = True
.EnableEvents = True
End With
End Sub
Functions:
Function LastRow(sh As Worksheet)
On Error Resume Next
LastRow = sh.Cells.Find(What:="*", _
After:=sh.Range("A1"), _
Lookat:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row
On Error GoTo 0
End Function
Function LastCol(sh As Worksheet)
On Error Resume Next
LastCol = sh.Cells.Find(What:="*", _
After:=sh.Range("A1"), _
Lookat:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByColumns, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Column
On Error GoTo 0
End Function
Instead of
Set CopyRng = sh.Range("A:B")
try
Set CopyRng = sh.Range("A1", sh.Range("B" & Rows.Count).End(xlUp))
as the former covers every row of the worksheet, hence the message box and the name running down the whole sheet.
Something like:
Option Explicit
Sub CopySheetNameToColumn()
Dim sh As Worksheet
Dim DestSh As Worksheet
Dim Last As Long
Dim CopyRng As Range
With Application
.ScreenUpdating = False
.EnableEvents = False
End With
Application.DisplayAlerts = False
On Error Resume Next
ActiveWorkbook.Worksheets("RDBMergeSheet").Delete
On Error GoTo 0
Application.DisplayAlerts = True
Set DestSh = ActiveWorkbook.Worksheets.Add
DestSh.Name = "RDBMergeSheet"
For Each sh In ActiveWorkbook.Worksheets
If sh.Name <> DestSh.Name Then
Last = GetLastRow(DestSh, 1)
With sh
Set CopyRng = sh.Range("A1:B" & GetLastRow(sh, 1))
End With
If Last + CopyRng.Rows.Count > DestSh.Rows.Count Then
MsgBox "There are not enough rows in the Destsh"
GoTo ExitTheSub
Else
CopyRng.Copy IIf(Last = 1, DestSh.Cells(1, "B"), DestSh.Cells(Last + 1, "B"))
End If
If Last = 1 Then
DestSh.Cells(Last, "A").Resize(CopyRng.Rows.Count).Value = sh.Name
Else
DestSh.Cells(Last + 1, "A").Resize(CopyRng.Rows.Count).Value = sh.Name
End If
End If
Next
ExitTheSub:
Application.Goto DestSh.Cells(1)
DestSh.Columns.AutoFit
With Application
.ScreenUpdating = True
.EnableEvents = True
End With
End Sub
Public Function GetLastRow(ByVal ws As Worksheet, Optional ByVal columnNumber As Long = 1) As Long
With ws
GetLastRow = .Cells(.Rows.Count, columnNumber).End(xlUp).Row
End With
End Function
You can shorten this significantly... there are lots of posts about getting items on a master sheet, 4 from yesterday alone.
Take a look at this:
Dim lrSrc As Long, lrDst As Long, i As Long
For i = 1 To Sheets.Count
If Not Sheets(i).Name = "Destination" Then
lrSrc = Sheets(i).Cells(Sheets(i).Rows.Count, "A").End(xlUp).Row
lrDst = Sheets("Destination").Cells(Sheets("Destination").Rows.Count, "A").End(xlUp).Row
With Sheets(i)
.Range(.Cells(2, "A"), .Cells(lrSrc, "B")).Copy Sheets("Destination").Range(Sheets("Destination").Cells(lrDst + 1, "B"), Sheets("Destination").Cells(lrDst + 1 + lrSrc, "C")) 'Assumes headers in first row aren't being copied
Sheets("Destination").Range(Sheets("Destination").Cells(lrDst + 1, "A"), Sheets("Destination").Cells(lrDst + 1 + lrSrc, "A")).Value = Sheets(i).Name
End With
End If
Next i
Code now tested
Screenshot of what is happening here, for simplicity sake, I have changed the values to represent the columns that they rightfully belong in
I am working on a program where I need to copy and reorganize data from multiple worksheets into one master. One row per sheet. From columns G to R I will need to set up an if statement, so that if a value on the sheet is greater than 0 it will be copy/pasted to the next available column in it's row. For testing I have eliminated the if statement, so that I always get a result. The problem I am having is that on the first row of data the "B" column is being overwritten, subsequent rows work as expected. Any ideas as to why this could be happening?
Sub CopyRangeFromMultiWorksheets()
Dim sh As Worksheet
Dim DestSh As Worksheet
Dim LastR As Long
Dim LastC As Long
With Application
.ScreenUpdating = False
.EnableEvents = False
End With
'Delete the sheet "Master" if it exist
Application.DisplayAlerts = False
On Error Resume Next
ActiveWorkbook.Worksheets("Master").Delete
On Error GoTo 0
Application.DisplayAlerts = True
'Add a worksheet with the name "Master"
Set DestSh = ActiveWorkbook.Worksheets.Add
DestSh.Name = "Master"
'loop through all worksheets and copy the data to the DestSh
For Each sh In ActiveWorkbook.Worksheets
If sh.Name <> DestSh.Name Then
'Find the last row with data on the DestSh
With ActiveSheet
LastR = .Cells(.Rows.Count, "a").End(xlUp).Row
End With
With ActiveSheet
LastC = .Cells(LastR, .Columns.Count).End(xlToLeft).Column
End With
sh.Range("B2").Copy
DestSh.Cells(LastR + 1, "A").PasteSpecial xlPasteValues 'customer'
DestSh.Cells(LastR + 1, "B").Value = ("Glass") 'Product"
DestSh.Cells(LastR + 1, "C").Value = sh.Name 'Color Name
sh.Range("H32").Copy
DestSh.Cells(LastR + 1, "D").PasteSpecial xlPasteValues 'based on QTY'
DestSh.Cells(LastR + 1, "E").Value = ("Liters") 'based on Units'
DestSh.Cells(LastR + 1, "F").Value = ("Clear") 'Base'
sh.Range("F13").Copy
DestSh.Cells(LastR + 1, LastC + 1).PasteSpecial xlPasteValues 'THIS IS THE LINE GIVING ME TROUBLE'
End If
Next
ExitTheSub:
Application.Goto DestSh.Cells(1)
'AutoFit the column width in the DestSh sheet
DestSh.Columns.AutoFit
With Application
.ScreenUpdating = True
.EnableEvents = True
End With
End Sub
Try to replace ActiveSheet with DestSh, probably this is the reason for the problem:
'Find the last row with data on the DestSh
With DestSh
LastR = .Cells(.Rows.Count, "a").End(xlUp).Row
End With
With DestSh
LastC = .Cells(LastR, .Columns.Count).End(xlToLeft).Column
End With
In your case, LastC = .Cells(LastR, .Columns.Count).End(xlToLeft).Column does not return the last column in the parent worksheet, but the last column in row LastR. Try this for the real last column:
LastC = LastRow(DestSh)
Function LastRow(sh As Worksheet)
On Error Resume Next
LastRow = sh.Cells.Find(What:="*", _
After:=sh.Range("A1"), _
Lookat:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row
On Error GoTo 0
End Function
And this is worth reading - https://www.rondebruin.nl/win/s9/win005.htm
Trying to find unique names in column B, and copy any rows with said name to new worksheet.
i.e. Alex clocks in twice this week he will fill two rows with data, I want to move his two rows of data to their own worksheet. Fred only clocks in once and creates 1 row of data, I want to move his row to a new worksheet.
Problem, it is copying row 2 to multiple of the new worksheets
link to my file: https://docs.google.com/spreadsheets/d/1JZla8ySwEotn91m8trh2_2fNLBNak-of98HQJ0YCP_0/edit?usp=sharing
code i'm using so far:
Sub Copy_To_Worksheets()
'Note: This macro use the function LastRow
Dim My_Range As Range
Dim FieldNum As Long
Dim CalcMode As Long
Dim ViewMode As Long
Dim ws2 As Worksheet
Dim Lrow As Long
Dim cell As Range
Dim CCount As Long
Dim WSNew As Worksheet
Dim ErrNum As Long
'Set filter range on ActiveSheet: A1 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("A1: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:E" & LastRow(ActiveSheet))
My_Range.Parent.Select
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
'This example filters 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, ......
FieldNum = 2
'Turn off AutoFilter
My_Range.Parent.AutoFilterMode = False
'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
'Add a worksheet to copy the a unique list and add the CriteriaRange
Set ws2 = Worksheets.Add
With ws2
'first we copy the Unique data from the filter field to ws2
My_Range.Columns(FieldNum).AdvancedFilter _
Action:=xlFilterCopy, _
CopyToRange:=.Range("A1"), Unique:=True
'loop through the unique list in ws2 and filter/copy to a new sheet
Lrow = .Cells(.Rows.Count, "A").End(xlUp).Row
For Each cell In .Range("A1:A" & Lrow)
'Filter the range
My_Range.AutoFilter Field:=FieldNum, Criteria1:="=" & _
Replace(Replace(Replace(cell.Value, "~", "~~"), "*", "~*"), "?", "~?")
'Check if there are no more then 8192 areas(limit of areas)
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 for the value : " & cell.Value _
& vbNewLine & "It is not possible to copy the visible data." _
& vbNewLine & "Tip: Sort your data before you use this macro.", _
vbOKOnly, "Split in worksheets"
Else
'Add a new worksheet
Set WSNew = Worksheets.Add(After:=Sheets(Sheets.Count))
On Error Resume Next
WSNew.Name = cell.Value
If Err.Number > 0 Then
ErrNum = ErrNum + 1
WSNew.Name = "Error_" & Format(ErrNum, "0000")
Err.Clear
End If
On Error GoTo 0
'Copy the visible data to the new worksheet
My_Range.SpecialCells(xlCellTypeVisible).Copy
With WSNew.Range("A1")
' 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
.Select
End With
End If
'Show all data in the range
My_Range.AutoFilter Field:=FieldNum
Next cell
'Delete the ws2 sheet
On Error Resume Next
Application.DisplayAlerts = False
.Delete
Application.DisplayAlerts = True
On Error GoTo 0
End With
'Turn off AutoFilter
My_Range.Parent.AutoFilterMode = False
If ErrNum > 0 Then
MsgBox "Rename every WorkSheet name that start with ""Error_"" manually" _
& vbNewLine & "There are characters in the name that are not allowed" _
& vbNewLine & "in a sheet name or the worksheet already exist."
End If
'Restore ScreenUpdating, Calculation, EnableEvents, ....
My_Range.Parent.Select
ActiveWindow.View = ViewMode
With Application
.ScreenUpdating = True
.EnableEvents = True
.Calculation = CalcMode
End With
End Sub
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
I would likely do it this way, but this would need more error checking.
Option Explicit
Sub MovePeeps()
Dim emp As New Collection
Dim ws, tmpWs, tw As Worksheet
Dim wb As Workbook
Dim empExist As Boolean
Dim i, j, k, m As Integer
Set wb = ThisWorkbook
Set ws = wb.ActiveSheet
empExist = False
'get unique employee names into the emp collection
'cycle through the used range - i= column of names
For i = 2 To ws.UsedRange.Rows.Count
'cycle through all peopel in the emp collection
For j = 1 To emp.Count
'check if person in cell = person in emp collection
If ws.Cells(i, 2) = emp(j) Then
empExist = True
Exit For
End If
Next j
'if person is in emp collection already reset empExist and exit loop without adding again
If empExist = True Then
empExist = False
Exit For
End If
'otherwise add that person to the collection
emp.Add ws.Cells(i, 2)
Next i
'create a worksheet named after each item in the emp collection
For i = 1 To emp.Count
wb.Worksheets.Add After:=wb.Worksheets(wb.Worksheets.Count)
Set tmpWs = wb.Worksheets(wb.Worksheets.Count)
tmpWs.Name = emp(i)
'add header row to each sheet
ws.Cells(1, 2).EntireRow.Copy Destination:=tmpWs.Cells(1, 1)
Next i
'copy all data to the new sheets
m = 1
For j = 1 To emp.Count
For Each tw In wb.Worksheets
'if the worksheet (tw) is the same name as the person in emp(j) then set the tmpWS variable
If tw.Name = emp(j) Then
Set tmpWs = tw
Exit For
End If
Next tw
For i = 2 To ws.UsedRange.Rows.Count
If ws.Cells(i, 2) = emp(j) Then
'find blank row on the sheet we are copying to
Do While tmpWs.Cells(m, 2) <> ""
m = m + 1
Loop
'copy the row to the tmpWS
ws.Cells(i, 2).EntireRow.Copy Destination:=tmpWs.Cells(m, 1)
End If
Next i
'reset our blank row counter.
m = 1
Next j
End Sub
I have for the most part it working. I can't seem to get through the CopyRng block to set it for each sheet and gather the entire row where the cells are color filled. Set CopyRng = sh.Cells().Interior.Color = vbOrange sh.Cells().EntireRowCan anyone help?
Module1:
Function LastRow(sh As Worksheet)
On Error Resume Next
LastRow = sh.Cells.Find(What:="*", _
After:=sh.Range("A1"), _
Lookat:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row
On Error GoTo 0
End Function
Function LastCol(sh As Worksheet)
On Error Resume Next
LastCol = sh.Cells.Find(What:="*", _
After:=sh.Range("A1"), _
Lookat:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByColumns, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Column
On Error GoTo 0
End Function
Module2:
Option Explicit
Sub CopyRangeFromMultiWorksheets()
Dim sh As Worksheet
Dim DestSh As Worksheet
Dim Last As Long
Dim CopyRng As Range
Dim tbl As ListObject
Dim Cell As Range
Dim clrOrange As Long
With Application
.ScreenUpdating = False
.EnableEvents = False
End With
' Delete the summary sheet if it exists.
Application.DisplayAlerts = False
On Error Resume Next
ThisWorkbook.Worksheets("SummarySheet").Delete
On Error GoTo 0
Application.DisplayAlerts = True
' Add a new summary worksheet.
Set DestSh = ThisWorkbook.Worksheets.Add
DestSh.Name = "SummarySheet"
Range("A1").FormulaR1C1 = "=TODAY()"
Range("A3:G3").Font.Bold = True
Range("A3") = "Vendor"
Range("B3") = "Account#"
Range("C3") = "Job/Dept"
Range("D3") = "Cost Code/Account"
Range("E3") = "PO"
Range("F3") = "Bill Date"
Range("G3") = "Bill Date2"
clrOrange = RGB(255, 192, 0)
' Loop through all worksheets and copy the data to the
' summary worksheet.
For Each sh In ThisWorkbook.Worksheets
For Each tbl In sh.ListObjects
For Each Cell In tbl.DataBodyRange
If sh.Name <> DestSh.Name Then
' Find the last row with data on the summary worksheet.
Last = LastRow(DestSh)
' Specify the range to place the data. Select entire row where cells are orange.
If Cell.Interior.Color = clrOrange Then
If CopyRng Is Nothing Then
Set CopyRng = Cell
Else
Set CopyRng = Union(CopyRng, Cell)
End If
End If
' This statement copies values and formats from each
' worksheet.
Cell.EntireRow.Copy
With DestSh.Cells(Last + 1, "A")
.PasteSpecial xlPasteValues
Application.CutCopyMode = False
End With
End If
Next
Next
Next
ExitTheSub:
Application.GoTo DestSh.Cells(1)
' AutoFit the column width in the summary sheet.
DestSh.Columns.AutoFit
With Application
.ScreenUpdating = True
.EnableEvents = True
End With
End Sub
You need to loop through the cells and check each to see if they are orange, then add them to CopyRng one by one:
Dim Cell as Range
For Each Cell in sh.Range("A1:A50") 'Or whatever the range is where orange cells can be
If Cell.Interior.Color = vbOrange Then
If CopyRng is Nothing then
Set CopyRng = Cell
Else
Set CopyRng = Union(CopyRng, Cell)
End If
EndIf
Next
CopyRng.Copy
etc.
I'm pretty clueless on this stuff, just starting to play with it. I have a code I got from a website, I customized it and it works great. It looks at a value in column 12 (a numeric value) on a master sheet, in my case "invoice2" and then copies that entire row based on the column 12 value to the pre-created sheet matching that value in my workbook. What I'd like is for it to only copy the row from columns A to H, not the entirety of columns A to L. I cannot for the life of me figure out where to adjust that in this code. Can anyone assist?
'<<<< Create a new sheet for every Unique value or paste it below the existing data if the sheet exists >>>>>
'This example copy all rows with the same value in the first column of
'the range to a new worksheet. It will do this for every unique value.
'The sheets will be named after the Unique value.
'If the sheet already exists the data will be pasted below the existing data on that worksheet.
'Note: this example use the function LastRow and SheetExists in the ModReset module
Sub Copy_To_Worksheets_2()
'Note: This macro use the function LastRow and SheetExists
Dim My_Range As Range
Dim FieldNum As Long
Dim CalcMode As Long
Dim ViewMode As Long
Dim ws2 As Worksheet
Dim Lrow As Long
Dim cell As Range
Dim CCount As Long
Dim WSNew As Worksheet
Dim ErrNum As Long
Dim DestRange As Range
Dim Lr As Long
'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("A12:L" & LastRow(ActiveSheet))
My_Range.Parent.Select
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
'This example filters 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, ......
FieldNum = 12
'Turn off AutoFilter
My_Range.Parent.AutoFilterMode = False
'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
'Add a worksheet to copy the a unique list and add the CriteriaRange
Set ws2 = Worksheets.Add
With ws2
'first we copy the Unique data from the filter field to ws2
My_Range.Columns(FieldNum).AdvancedFilter _
Action:=xlFilterCopy, _
CopyToRange:=.Range("A1"), Unique:=True
'loop through the unique list in ws2 and filter/copy to a new sheet
Lrow = .Cells(Rows.count, "A").End(xlUp).Row
For Each cell In .Range("A2:A" & Lrow)
My_Range.Parent.Select
'Filter the range
My_Range.AutoFilter Field:=FieldNum, Criteria1:="=" & _
Replace(Replace(Replace(cell.Value, "~", "~~"), "*", "~*"), "?", "~?")
'Check if there are no more then 8192 areas(limit of areas)
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 for the value: " & cell.Value _
& vbNewLine & "It is not possible to copy the visible data." _
& vbNewLine & "Tip: Sort your data before you use this macro.", _
vbOKOnly, "Split in worksheets"
Else
'Add a new worksheet or set a reference to a existing sheet
If SheetExists(cell.Text) = False Then
Set WSNew = Worksheets.Add(After:=Sheets(Sheets.count))
On Error Resume Next
WSNew.Name = cell.Value
If Err.Number > 0 Then
ErrNum = ErrNum + 1
WSNew.Name = "Error_" & Format(ErrNum, "0000")
Err.Clear
End If
On Error GoTo 0
Set DestRange = WSNew.Range("A1")
Else
Set WSNew = Sheets(cell.Text)
Lr = LastRow(WSNew)
Set DestRange = WSNew.Range("A" & Lr + 1)
End If
'Copy the visible data to the worksheet
My_Range.SpecialCells(xlCellTypeVisible).Copy
With DestRange
.Parent.Select
' Paste:=8 will copy the columnwidth in Excel 2000 and higher
' Remove this line if you use Excel 97
.PasteSpecial xlPasteValues
.PasteSpecial xlPasteFormats
Application.CutCopyMode = False
.Select
End With
End If
' Delete the header row if you copy to a existing worksheet
If Lr > 1 Then WSNew.Range("A" & Lr + 1).EntireRow.Delete
'Show all data in the range
My_Range.AutoFilter Field:=FieldNum
Next cell
'Delete the ws2 sheet
On Error Resume Next
Application.DisplayAlerts = False
.Delete
Application.DisplayAlerts = True
On Error GoTo 0
End With
'Turn off AutoFilter
My_Range.Parent.AutoFilterMode = False
If ErrNum > 0 Then
MsgBox "Rename every WorkSheet name that start with ""Error_"" manually" _
& vbNewLine & "There are characters in the name that are not allowed" _
& vbNewLine & "in a sheet name or the worksheet already exist."
End If
'Restore ScreenUpdating, Calculation, EnableEvents, ....
My_Range.Parent.Select
ActiveWindow.View = ViewMode
With Application
.ScreenUpdating = True
.EnableEvents = True
.Calculation = CalcMode
End With
End Sub
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
Function SheetExists(SName As String, _
Optional ByVal WB As Workbook) As Boolean
'Chip Pearson
On Error Resume Next
If WB Is Nothing Then Set WB = ThisWorkbook
SheetExists = CBool(Len(WB.Sheets(SName).Name))
End Function
I have changed your code slightly :) Now it yields what you wanted.
The current version of code:
'<<<< Create a new sheet for every Unique value or paste it below the existing data if the sheet exists >>>>>
'This example copy all rows with the same value in the first column of
'the range to a new worksheet. It will do this for every unique value.
'The sheets will be named after the Unique value.
'If the sheet already exists the data will be pasted below the existing data on that worksheet.
'Note: this example use the function LastRow and SheetExists in the ModReset module
Sub Copy_To_Worksheets_2()
'Note: This macro use the function LastRow and SheetExists
Dim My_Range As Range
Dim Filter_Range As Range
Dim FieldNum As Long
Dim CalcMode As Long
Dim ViewMode As Long
Dim ws2 As Worksheet
Dim Lrow As Long
Dim cell As Range
Dim CCount As Long
Dim WSNew As Worksheet
Dim ErrNum As Long
Dim DestRange As Range
Dim Lr As Long
'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.
With ActiveSheet
Set My_Range = .Range("A12:H" & LastRow(ActiveSheet))
Set Filter_Range = .Range("L12:L" & LastRow(ActiveSheet))
.Select
End With
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
'This example filters 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, ......
FieldNum = 12
'Turn off AutoFilter
My_Range.Parent.AutoFilterMode = False
'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
'Add a worksheet to copy the a unique list and add the CriteriaRange
Set ws2 = Worksheets.Add
With ws2
'first we copy the Unique data from the filter field to ws2
Filter_Range.AdvancedFilter _
Action:=xlFilterCopy, _
CopyToRange:=.Range("A1"), Unique:=True
'loop through the unique list in ws2 and filter/copy to a new sheet
Lrow = .Cells(Rows.Count, "A").End(xlUp).Row
For Each cell In .Range("A2:A" & Lrow)
My_Range.Parent.Select
'Filter the range
Filter_Range.AutoFilter Field:=1, Criteria1:="=" & _
Replace(Replace(Replace(cell.Value, "~", "~~"), "*", "~*"), "?", "~?")
'Check if there are no more then 8192 areas(limit of areas)
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 for the value: " & cell.Value _
& vbNewLine & "It is not possible to copy the visible data." _
& vbNewLine & "Tip: Sort your data before you use this macro.", _
vbOKOnly, "Split in worksheets"
Else
'Add a new worksheet or set a reference to a existing sheet
If SheetExists(cell.Text) = False Then
Set WSNew = Worksheets.Add(After:=Sheets(Sheets.Count))
On Error Resume Next
WSNew.Name = cell.Value
If Err.Number > 0 Then
ErrNum = ErrNum + 1
WSNew.Name = "Error_" & Format(ErrNum, "0000")
Err.Clear
End If
On Error GoTo 0
Set DestRange = WSNew.Range("A1")
Else
Set WSNew = Sheets(cell.Text)
Lr = LastRow(WSNew)
Set DestRange = WSNew.Range("A" & Lr + 1)
End If
'Copy the visible data to the worksheet
My_Range.SpecialCells(xlCellTypeVisible).Copy
With DestRange
.Parent.Select
' Paste:=8 will copy the columnwidth in Excel 2000 and higher
' Remove this line if you use Excel 97
.PasteSpecial xlPasteValues
.PasteSpecial xlPasteFormats
Application.CutCopyMode = False
.Select
End With
End If
' Delete the header row if you copy to a existing worksheet
If Lr > 1 Then WSNew.Range("A" & Lr + 1).EntireRow.Delete
'Show all data in the range
Filter_Range.AutoFilter 'Field:=FieldNum
Next 'cell
'Delete the ws2 sheet
On Error Resume Next
Application.DisplayAlerts = False
.Delete
Application.DisplayAlerts = True
On Error GoTo 0
End With
'Turn off AutoFilter
My_Range.Parent.AutoFilterMode = False
If ErrNum > 0 Then
MsgBox "Rename every WorkSheet name that start with ""Error_"" manually" _
& vbNewLine & "There are characters in the name that are not allowed" _
& vbNewLine & "in a sheet name or the worksheet already exist."
End If
'Restore ScreenUpdating, Calculation, EnableEvents, ....
My_Range.Parent.Select
ActiveWindow.View = ViewMode
With Application
.ScreenUpdating = True
.EnableEvents = True
.Calculation = CalcMode
End With
End Sub
Function LastRow(sh As Worksheet) As Long
LastRow = sh.Range("A1").SpecialCells(xlCellTypeLastCell).Row
End Function
Function SheetExists(SName As String, Optional ByVal WB As Workbook) As Boolean
'Chip Pearson
On Error Resume Next
If WB Is Nothing Then Set WB = ThisWorkbook
SheetExists = CBool(Len(WB.Sheets(SName).Name))
End Function
Changes are basically related to the newly added Filter_Range. My_Range remains, but while the subroutine is processing, fields are no longer filtered according to the 12th column of My_Range. Now filter works on the first (the only) column of Filter_Range. In the code you can see assigned values for both of them.
Set My_Range = .Range("A12:H" & LastRow(ActiveSheet))
Set Filter_Range = .Range("L12:L" & LastRow(ActiveSheet))
LastRow function was also changed, now it has only one line:
Function LastRow(sh As Worksheet) As Long
LastRow = sh.Range("A1").SpecialCells(xlCellTypeLastCell).Row
End Function
Try it out, it works! :)