When I run my code more than one time it will duplicate results in sheets. I need to remove the previous data and paste the new data every time I run it.
Sub CreateMonthlySheets()
Dim lastRow, mMonth, tstDate1, tstDate2, shtName, nxtRow
On Error Resume Next
'Turn off ScreenUpdating
Application.ScreenUpdating = False
'Make a copy of the data sheet and sort by date
Sheets("Main Data Sheet").Copy After:=Sheets(1)
Sheets(2).Name = "SortTemp"
With Sheets("SortTemp")
lastRow = .Cells(Rows.Count, 1).End(xlUp).Row
Rows("2:" & lastRow).Sort Key1:=Range("C2"), Order1:=xlAscending
'Using SortTemp Sheet, create monthly sheets by
'testing Month and Year values in Column A
'Loop through dates
For Each mMonth In .Range("C2:C" & lastRow)
tstDate1 = Month(mMonth) & Year(mMonth)
tstDate2 = Month(mMonth.Offset(-1, 0)) & Year(mMonth.Offset(-1, 0))
'If Month and Year are different than cell above, create new sheet
If tstDate1 <> tstDate2 Then
ActiveWorkbook.Sheets.Add After:=Worksheets(Worksheets.Count)
'Name the sheet based on the Month and Year
ActiveSheet.Name = MonthName(Month(mMonth)) & " " & Year(mMonth)
'Copy Column Widths and Header Row
.Rows(1).Copy
ActiveSheet.Rows(1).PasteSpecial Paste:=8 'ColumnWidth
ActiveSheet.Rows(1).PasteSpecial 'Data and Formats
End If
Next
On Error GoTo 0
'Loop through dates, copying row to the correct sheet
For Each mMonth In .Range("C2:C" & lastRow)
'Create sheetname variable
shtName = MonthName(Month(mMonth)) & " " & Year(mMonth)
'Determine next empty row in sheet
nxtRow = Sheets(shtName).Cells(Rows.Count, 1).End(xlUp).Row + 1
'Copy Data
.Range(mMonth.Address).EntireRow.Copy Destination:=Sheets(shtName).Cells(nxtRow, 1)
Next
End With
'Delete SortTemp sheet
Application.DisplayAlerts = False
Sheets("SortTemp").Delete
Application.DisplayAlerts = True
'Turn on ScreenUpdating
Application.ScreenUpdating = True
End Sub
Try this
Option Explicit
Sub CreateMonthlySheets()
Dim mMonth As Range
Dim shtName As String
Dim monthSht As Worksheet
Dim newSheet As Boolean
' 'Turn off ScreenUpdating
Application.ScreenUpdating = False
'Make a copy of the data sheet and sort by date
With GetSheet("SortTemp", True, newSheet) '<-- get your "temp" sheet: if not existent then create it
If Not newSheet Then .Cells.Clear '<--| if it existed then clear it
Sheets("Main Data Sheet").UsedRange.Copy Destination:=.Cells(1, 1) '<--| fill it with "Main Data Sheet" sheet
'Using SortTemp Sheet, create monthly sheets by
'testing Month and Year values in Column A
'Loop through dates
For Each mMonth In .Range("C2:C" & .Cells(.Rows.Count, 1).End(xlUp).row)
shtName = MonthName(Month(mMonth)) & " " & Year(mMonth) '<--| build "month" sheet name
Set monthSht = GetSheet(shtName, False, newSheet) 'Set "month" sheet: if not existent then create it
If newSheet Then '<--| if it didn't exist...
'...Copy Column Widths and Header Row
.Rows(1).Copy
monthSht.Rows(1).PasteSpecial Paste:=8 'ColumnWidth
monthSht.Rows(1).PasteSpecial 'Data and Formats
Else 'otherwise...
monthSht.UsedRange.Offset(1).Clear '<--| ...clear it from row 2 downwards (assuming row 1 has at least one value...)
End If
'Copy Data
mMonth.EntireRow.Copy Destination:=monthSht.Cells(monthSht.Rows.Count, 1).End(xlUp).Offset(1)
Next
End With
'Delete SortTemp sheet
Application.DisplayAlerts = False
Sheets("SortTemp").Delete
Application.DisplayAlerts = True
'Turn on ScreenUpdating
Application.ScreenUpdating = True
End Sub
'Sub main()
' Dim sh As Worksheet
' Dim existent As Boolean
'
' Set sh = GetSheet("data1", False, existent)
'
'End Sub
Function GetSheet(shtName As String, Optional okClear As Boolean = False, Optional newSheet As Boolean = False) As Worksheet
On Error Resume Next
Set GetSheet = Worksheets(shtName)
On Error GoTo 0
If GetSheet Is Nothing Then
newSheet = True
Set GetSheet = ActiveWorkbook.Sheets.Add(After:=Worksheets(Worksheets.Count))
GetSheet.Name = shtName
Else
If okClear Then GetSheet.Cells.Clear
newSheet = False
End If
End Function
which results from:
avoid On Error Resume Next ruling for more than strictly needed
no need to loop twice
I Found The Solution>>thanks For all
Option Explicit
Sub CreateMonthlySheets()
Dim mMonth As Range
Dim shtName As String
Dim monthSht As Worksheet
Dim newSheet As Boolean
' 'Turn off ScreenUpdating
Application.ScreenUpdating = False
'Make a copy of the data sheet and sort by date
With GetSheet("SortTemp", True, newSheet) '<-- get your "temp" sheet: if not existent then create it
If Not newSheet Then .Cells.Clear '<--| if it existed then clear it
Sheets("Main Data Sheet").UsedRange.Copy Destination:=.Cells(1, 1) '<--| fill it with "Main Data Sheet" sheet
'Using SortTemp Sheet, create monthly sheets by
'testing Month and Year values in Column A
'Loop through dates
For Each mMonth In .Range("C2:C" & .Cells(.Rows.Count, 1).End(xlUp).Row)
shtName = MonthName(Month(mMonth)) & Year(mMonth) '<--| build "month" sheet name
Set monthSht = GetSheet(shtName, False, newSheet) 'Set "month" sheet: if not existent then create it
monthSht.UsedRange.Offset(1).Clear
Next
For Each mMonth In .Range("C2:C" & .Cells(.Rows.Count, 1).End(xlUp).Row)
shtName = MonthName(Month(mMonth)) & Year(mMonth) '<--| build "month" sheet name
Set monthSht = GetSheet(shtName, False, newSheet) 'Set "month" sheet: if not existent then create it
' monthSht.UsedRange.Offset(1).Clear
' If newSheet Then '<--| if it didn't exist...
'...Copy Column Widths and Header Row
.Rows(1).Copy
monthSht.Rows(1).PasteSpecial Paste:=8 'ColumnWidth
monthSht.Rows(1).PasteSpecial 'Data and Formats
' Else 'otherwise...
'monthSht.UsedRange.Offset(1).Clear '<--| ...clear it from row 2 downwards (assuming row 1 has at least one value...)
' End If
'Copy Data
mMonth.EntireRow.Copy Destination:=monthSht.Cells(monthSht.Rows.Count, 1).End(xlUp).Offset(1)
Next
End With
'Delete SortTemp sheet
Application.DisplayAlerts = False
Sheets("SortTemp").Delete
Application.DisplayAlerts = True
'Turn on ScreenUpdating
Application.ScreenUpdating = True
End Sub
Function GetSheet(shtName As String, Optional okClear As Boolean = False, Optional newSheet As Boolean = False) As Worksheet
On Error Resume Next
Set GetSheet = Worksheets(shtName)
On Error GoTo 0
If GetSheet Is Nothing Then
newSheet = True
Set GetSheet = ActiveWorkbook.Sheets.Add(After:=Worksheets(Worksheets.Count))
GetSheet.Name = shtName
Else
If okClear Then GetSheet.Cells.Clear
newSheet = False
End If
End Function
Related
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
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 am trying to achieve the following.
When I enter a value on 'Master' worksheet in the Range A5:A50, a macro is run which creates a new worksheet with the same name as the value and then copies the template onto the new sheet.
In addition to this I would also like to copy the value adjacent to the value enter on Master worksheet to this new worksheet so it does calculations automatically.
For example I enter '1' in A5 and '2' in B5. I would like to create a new worksheet with name '1', copy the template from 'Template' worksheet and copy the value of B5 on to the new worksheet named '1'.
I have following code but it also tries to copy Template worksheet with macro is run which results in an error because a worksheet with name 'Template' already exists.
Sub CreateAndNameWorksheets()
Dim c As Range
Application.ScreenUpdating = False
For Each c In Sheets("Master").Range("A5:A50")
Sheets("Template").Copy After:=Sheets(Sheets.Count)
With c
ActiveSheet.Name = .Value
.Parent.Hyperlinks.Add Anchor:=c, Address:="", SubAddress:= _
"'" & .Text & "'!A1", TextToDisplay:=.Text
End With
Next c
Application.ScreenUpdating = True
End Sub
Right-click the Master worksheet's name tab and select View Code. When the VBE opens up, paste the following into the window titled something like Book1 - Master (Code).
Private Sub Worksheet_Change(ByVal target As Range)
If Not Intersect(target, Rows("5:50"), Columns("A:B")) Is Nothing Then
On Error GoTo bm_Safe_Exit
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.DisplayAlerts = False
Application.Calculation = xlCalculationManual
Dim r As Long, rw As Long, w As Long
For r = 1 To Intersect(target, Rows("5:50"), Columns("A:B")).Rows.Count
rw = Intersect(target, Rows("5:50"), Columns("A:B")).Rows(r).Row
If Application.CountA(Cells(rw, 1).Resize(1, 2)) = 2 Then
For w = 1 To Worksheets.Count
If LCase(Worksheets(w).Name) = LCase(Cells(rw, 1).Value2) Then Exit For
Next w
If w > Worksheets.Count Then
Worksheets("Template").Visible = True
Worksheets("Template").Copy after:=Sheets(Sheets.Count)
With Sheets(Sheets.Count)
.Name = Cells(rw, 1).Value2
.Cells(1, 1) = Cells(rw, 2).Value
End With
End If
With Cells(rw, 1)
.Parent.Hyperlinks.Add Anchor:=Cells(rw, 1), Address:="", _
SubAddress:="'" & .Value2 & "'!A1", TextToDisplay:=.Value2
End With
End If
Next r
Me.Activate
End If
bm_Safe_Exit:
Worksheets("Template").Visible = xlVeryHidden
Me.Activate
Application.Calculation = xlCalculationAutomatic
Application.DisplayAlerts = True
Application.EnableEvents = True
Application.ScreenUpdating = True
End Sub
Note that this depends on you having a worksheet named Template in order to generate the new worksheets. It also keeps the Template worksheet xlVeryHidden which means that it will not show up if you try to unhide it. Go into the VBE and use the Properties window (e.g. F4) to set the visibility to visible.
This routine should survive pasting multiple values into A2:B50 but it will discard proposed worksheet names in column A that already exists. There must be a value i both column A and column B of any row before it will proceed.
There are currently no checks for illegal worksheet name characters. You may want to familiarize yourself with those and add some error checking.
Another example relevant to the post title but not the specific application. Code updates sheets in master list with list row number creating sheet from template if it doesn't exist.
Other reference: https://stackoverflow.com/a/18411820/9410024.
Sub UpdateTemplateSheets()
' Update sheets in list created from a template
'
' Input: List on master sheet, template sheet
' Output: Updated sheet from template for each item in list
'
Dim wsInitial As Worksheet
Dim wsMaster As Worksheet
Dim wsTemp As Worksheet
Dim lVisibility As XlSheetVisibility
Dim strSheetName As String
Dim rIndex As Long
Dim i As Long
On Error GoTo Safe_Exit
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.DisplayAlerts = False
' Application.Calculation = xlCalculationManual
Set wsInitial = ActiveSheet
Set wsMaster = Sheets("Summary")
Set wsTemp = Sheets("Template")
lVisibility = wsTemp.Visible ' In case template sheet is hidden
wsTemp.Visible = xlSheetVisible
For rIndex = 2 To wsMaster.Cells(Rows.Count, "A").End(xlUp).Row
' Ensure valid sheet name
strSheetName = wsMaster.Cells(rIndex, "A").Text
For i = 1 To 7
strSheetName = Replace(strSheetName, Mid(":\/?*[]", i, 1), " ")
Next i
strSheetName = Trim(Left(WorksheetFunction.Trim(strSheetName), 31))
' Ensure sheet name doesn't already exist
If Not Evaluate("IsRef('" & strSheetName & "'!A1)") Then
wsTemp.Copy after:=Sheets(Sheets.Count)
With Sheets(Sheets.Count)
.Name = strSheetName
End With
End If
With Sheets(strSheetName)
.Range("B59").Value = rIndex * 16 + 1 ' Update template block option row
End With
Next rIndex
Safe_Exit:
Application.ScreenUpdating = True
Application.EnableEvents = True
Application.DisplayAlerts = True
'Application.Calculation = xlCalculationAutomatic
wsInitial.Activate
wsTemp.Visible = lVisibility ' Set template sheet to its original visible state
End Sub
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! :)
I need to consolidate multiple worksheets in to one worksheet while having a space left between each tab of consolidated information. Can anyone help with this? Below is the code I have but I'm missing something:
Sub CopyWorksheets()
Dim wrk As Workbook
Dim sht As Worksheet
Dim trg As Worksheet
Dim rng As Range
Dim colCount As Integer
Set wrk = ActiveWorkbook 'Working in active workbook
For Each sht In wrk.Worksheets
If sht.Name = "Master" Then
MsgBox "There is a worksheet called as 'Master'." & vbCrLf & _
"Please remove or rename this worksheet since 'Master' would be" & _
"the name of the result worksheet of this process.", _
vbOKOnly + vbExclamation, "Error"
Exit Sub
End If
Next sht
'We don't want screen updating
Application.ScreenUpdating = False
'Add new worksheet as the last worksheet
Set trg = wrk.Worksheets.Add(After:=wrk.Worksheets(wrk.Worksheets.Count))
'Rename the new worksheet
trg.Name = "Master"
'Get column headers from the first worksheet
'Column count first
Set sht = wrk.Worksheets(1)
colCount = sht.Cells(1, 255).End(xlToLeft).Column
'Now retrieve headers, no copy&paste needed
With trg.Cells(1, 1).Resize(1, colCount)
.Value = sht.Cells(1, 1).Resize(1, colCount).Value
'Set font as bold
.Font.Bold = True
End With
'We can start loop
For Each sht In wrk.Worksheets
'If worksheet in loop is the last one, stop execution (it is Master worksheet)
If sht.Index = wrk.Worksheets.Count Then
Exit For
End If
'Data range in worksheet - starts from second row as
'first rows are the header rows in all worksheets
Set rng = sht.Range(sht.Cells(2, 1), sht.Cells(65536, 1).End(xlUp).Resize(, colCount))
'Put data into the Master worksheet
trg.Cells(65536, 1).End(xlUp).Offset(1).Resize(rng.Rows.Count, _
rng.Columns.Count).Value = rng.Value
'move cursor to bottom on active range and insert row
Range("A65536").End(xlUp).Offset(1, 0).Select
Selection.Offset(1, 0).Select
Next sht
'Fit the columns in Master worksheet
trg.Columns.AutoFit
'Screen updating should be activated
Application.ScreenUpdating = True
End Sub
Maybe this is what you need:
For Each sht In wrk.Worksheets
If sht.Index = wrk.Worksheets.Count Then Exit For
Set rng = sht.Range(sht.Cells(2, 1), _
sht.Cells(rows.count, 1).End(xlUp).Resize(, colCount))
'Put data into the Master worksheet (skip one empty row)
trg.Cells(rows.count, 1).End(xlUp).Offset(2).Resize(rng.Rows.Count, _
rng.Columns.Count).Value = rng.Value
Next sht