Use a Cell Value as a Worksheet Name - excel
I want to paste data from a Workbook to another workbook into a sheet which has the name of a cell value. I don't know if that's possible, but I'm struggling with that and I can't find anything similar on internet.
This is my code so far:
'This creates a sheet from a range and gives it the name of the cell so it can be from 5 to 10 sheets'
For Each Cell In Range("G5:G15")
If Cell.Value <> "" Then
Sheets.Add(After:=Sheets(Sheets.Count)).Name = Cell.Value
End If
Next
After other code which is not important, I made this:
Dim AutoFilterRng As Range
Dim WorksheetName As String
For Each Cell In Range("H5", Range("H5").End(xlDown))
If Cell.Value <> "" Then
WorksheetName = Cell.Offset(0, -1).Value
Workbooks.Open MJFile 'Opens the file where data I want to copy
ActiveSheet.Range("A:U").AutoFilter Field:=12, Criteria1:="*" & Cell.Value 'Filters depending on the cell value
With ActiveSheet.AutoFilter.Range
Set AutoFilterRng = .Offset(1, 0).Resize(.Rows.Count - 1, 1).SpecialCells(xlCellTypeVisible)
End With
ActiveSheet.AutoFilter.Range.Offset(1, 0).Resize(ActiveSheet.AutoFilter.Range.Count - 1).Copy
Workbooks.Open WBOR 'Opens the Workbook where I want to paste data
Worksheets(WorksheetName).Range("A1").Paste 'This gives an error and it is where I would like to paste my data
Workbooks.Open MJFile
AutoFilterMode = False
End If
Next
Thank you very much in advance
If you want to see the whole code:
Sub AddTO()
Application.Calculation = xlManual
Application.ScreenUpdating = False
Application.EnableEvents = False
'------------------------------------------------------------------------------------------------------------------------------------------------------'
'Open TO FIle'
Dim WBOR As String
Dim MJFile As String
Dim TOFile As String
Dim Path As String
WBOR = ActiveWorkbook.Path & "\" & ActiveWorkbook.Name
'On Error GoTo Fin
MsgBox "Choose Bear File"
With Application.FileDialog(msoFileDialogFilePicker)
.Filters.Clear
.AllowMultiSelect = False
If .Show = -1 Then
TOFile = .SelectedItems(1)
End If
End With
Workbooks.Open TOFile
'Filter Bear File to Only Necessary TO'
Dim NameRng As Range
Dim TORng As Range
Dim DeliveryWeek As String
Dim i As Long
Workbooks.Open WBOR
Set NameRng = Worksheets("Tasks_Orders_Info").Range("E5", Range("E5").End(xlDown))
Workbooks.Open TOFile
Set TORng = Worksheets("WS Lead Plan1").Range("G2", Range("G2").End(xlDown))
Workbooks.Open WBOR
DeliveryWeek = "*Week_" & Worksheets("Tasks_Orders_Info").Range("C5").Value & "*"
Workbooks.Open TOFile
For i = TORng.Count To 1 Step -1
Select Case True
Case TORng.Cells(i) Like DeliveryWeek
Case Else
TORng.Cells(i).EntireRow.Delete
End Select
Next i
'Add TO to MJ File'
Workbooks.Open WBOR
TORng.Copy
Worksheets("Tasks_Orders_Info").Range("G5").PasteSpecial xlPasteValues
Worksheets("Tasks_Orders_Info").Range("G5").End(xlDown).PasteSpecial xlPasteValues
Workbooks.Open TOFile
ActiveWorkbook.Close SaveChanges:=False
Range("H5:H15") = "=IF(ISERR(FIND("" "",Table2[#Coder])),"""",LEFT(Table2[#Coder],FIND("" "",Table2[#Coder])-1))"
Range("I5:I15") = "=MID(Table2[#Coder],SEARCH("" "",Table2[#Coder],1)+1,SEARCH("" "", Table2[#Coder],SEARCH("" "",Table2[#Coder],1)+1)-SEARCH("" "",Table2[#Coder],1))"
Range("J5:J15") = "=IFERROR(MID(Table2[#Coder],FIND("" "",Table2[#Coder],FIND("" "",Table2[#Coder])+1)+1,FIND("" "",Table2[#Coder],FIND("" "",Table2[#Coder],FIND("" "",Table2[#Coder])+1)+1)-FIND("" "",Table2[#Coder],FIND("" "",Table2[#Coder])+1)-1),"""")"
Form1 = "=IF(OR(ISNUMBER(FIND(H5,G5,1)),ISNUMBER(FIND(I5,G5,1)),IF(J5="""",FALSE,ISNUMBER(FIND(J5,G5,1)))),LEFT(G5,FIND("" "",G5,1)-3),IF(OR(ISNUMBER(FIND(H5,G6,1)),ISNUMBER(FIND(I5,G6,1)),IF(J5="""",FALSE,ISNUMBER(FIND(J5,G6,1)))),LEFT(G6,FIND("" "",G6,1)-3),IF(OR(ISNUMBER(FIND(H5,G7,1)),ISNUMBER(FIND(I5,G7,1)),IF(J5="""",FALSE,ISNUMBER(FIND(J5,G7,1)))),LEFT(G7,FIND("" "",G7,1)-3),IF(OR(ISNUMBER(FIND(H5,G8,1)),ISNUMBER(FIND(I5,G8,1)),IF(J5="""",FALSE,ISNUMBER(FIND(J5,G8,1)))),LEFT(G8,FIND("" "",G8,1)-3),IF(OR("
Form2 = "ISNUMBER(FIND(H5,G9,1)),ISNUMBER(FIND(I5,G9,1)),IF(J5="""",FALSE,ISNUMBER(FIND(J5,G9,1)))),LEFT(G9,FIND("" "",G9,1)-3),IF(OR(ISNUMBER(FIND(H5,G10,1)),ISNUMBER(FIND(I5,G10,1)),IF(J5="""",FALSE,ISNUMBER(FIND(J5,G10,1)))),LEFT(G10,FIND("" "",G10,1)-3),IF(OR(ISNUMBER(FIND(H5,G11,1)),ISNUMBER(FIND(I5,G11,1)),IF(J5="""",FALSE,ISNUMBER(FIND(J5,G11,1)))),LEFT(G11,FIND("" "",G11,1)-3),IF(OR(ISNUMBER(FIND(H5,G12,1)),ISNUMBER(FIND(I5,G12,1)),IF(J5="""",FALSE,ISNUMBER(FIND(J5,G12,1)))),LEFT(G12,FIND("" "",G12,1)-3),IF("
Form3 = "OR(ISNUMBER(FIND(H5,G13,1)),ISNUMBER(FIND(I5,G13,1)),IF(J5="""",FALSE,ISNUMBER(FIND(J5,G13,1)))),LEFT(G13,FIND("" "",G13,1)-3),IF(OR(ISNUMBER(FIND(H5,G14,1)),ISNUMBER(FIND(I5,G14,1)),IF(J5="""",FALSE,ISNUMBER(FIND(J5,G14,1)))),LEFT(G14,FIND("" "",G14,1)-3),IF(OR(ISNUMBER(FIND(H5,G15,1)),ISNUMBER(FIND(I5,G15,1)),IF(J5="""",FALSE,ISNUMBER(FIND(J5,G15,1)))),LEFT(G15,FIND("" "",G15,1)-3),""NOT FOUND"")))))))))))"
Range("B5", Range("B5").End(xlDown)) = Form1 + Form2 + Form3
Range("B5", Range("B5").End(xlDown)).Copy
Range("B5", Range("B5").End(xlDown)).PasteSpecial xlPasteValues
Range("G5", Range("G5").End(xlDown)).ClearContents
'Create New Sheets"
Range("G5:G15") = "=IFERROR(CONCAT(RIGHT(Table2[#[TASK ORDER]],LEN(Table2[#[TASK ORDER]])-SEARCH("" TO"",Table2[#[TASK ORDER]],1)),""_"",H5),"""")"
Range("G5:G15").Copy
Range("G5:G15").PasteSpecial xlPasteValues
Range("H5", Range("H5").End(xlDown)).Select
Range(Selection, Selection.End(xlToRight)).Delete
For Each Cell In Range("G5:G15")
If Cell.Value <> "" Then
Sheets.Add(After:=Sheets(Sheets.Count)).Name = Cell.Value
End If
Next
Worksheets("Tasks_Orders_Info").Activate
'Open MJ File'
MsgBox "Choose mj extraction"
With Application.FileDialog(msoFileDialogFilePicker)
.Filters.Clear
.AllowMultiSelect = False
If .Show = -1 Then
MJFile = .SelectedItems(1)
End If
End With
Workbooks.Open MJFile
'Delete non Users'
Dim mapjobdata As Range
Dim WorkUserRg As Range
Worksheets("map_jobs_-_feedback_and_observa").Range("A1").Select
Worksheets("map_jobs_-_feedback_and_observa").Range(Selection, Selection.End(xlDown)).Select
Worksheets("map_jobs_-_feedback_and_observa").Range(Selection, Selection.End(xlToRight)).Select
Set mapjobdata = Worksheets("map_jobs_-_feedback_and_observa").Range(Selection.Address)
Set WorkUserRg = mapjobdata.Find("Worked on by User", , xlValues, xlWhole, , , True).Offset(1, 0)
Set WorkUserRg = Worksheets("map_jobs_-_feedback_and_observa").Range(WorkUserRg, WorkUserRg.End(xlDown))
For i = WorkUserRg.Count To 1 Step -1
If WorkUserRg.Cells(i) Like "*#email.com*" Then
Else
WorkUserRg.Cells(i).EntireRow.Delete
End If
Next i
'Add MapJobs to each Sheet'
Workbooks.Open WBOR
Range("H5:H15") = "=IFERROR(RIGHT(Table2[#Coder],FIND("")"",Table2[#Coder],1)-(FIND("" ("",Table2[#Coder],1))),"""")"
Range("H5", Range("H5").End(xlDown)).Copy
Range("H5", Range("H5").End(xlDown)).PasteSpecial xlPasteValues
Dim AutoFilterRng As Range
Dim WorksheetName As String
For Each Cell In Range("H5", Range("H5").End(xlDown))
If Cell.Value <> "" Then
WorksheetName = Cell.Offset(0, -1).Value
Workbooks.Open MJFile
ActiveSheet.Range("A:U").AutoFilter Field:=12, Criteria1:="*" & Cell.Value
With ActiveSheet.AutoFilter.Range
Set AutoFilterRng = .Offset(1, 0).Resize(.Rows.Count - 1, 1).SpecialCells(xlCellTypeVisible)
End With
ActiveSheet.AutoFilter.Range.Offset(1, 0).Resize(ActiveSheet.AutoFilter.Range.Count - 1).Copy
Workbooks.Open WBOR
Worksheets(WorksheetName).Range("A1").Paste
Workbooks.Open MJFile
AutoFilterMode = False
End If
Next
'------------------------------------------------------------------------------------------------------------------------------------------------------'
Fin:
Application.EnableEvents = True
Application.Calculation = xlAutomatic
Application.ScreenUpdating = True
End Sub
This is the error I get and debug shows the next line:
This is an untested code. I do not have the necessary data to test it. It must give you some hints in order to understand what is to be done:
Please add Option Explicit on top of your module. This will oblige you to declare all variables...
Sub sheetsAddAndCopy()
Dim WBOR As Workbook, Wmjf As Workbook, shW As Worksheet, shMJ As Worksheet
Dim AutoFilterRng As Range, WorksheetName As String, cell As Range
Const MJFile As String = "your workbook full path"
Set WBOR = ThisWorkbook
Set Wmjf = Workbooks.Open(MJFile) 'Opens the file where data I want to copy
For Each cell In WBOR.Range("H5", Range("H5").End(xlDown))
If cell.Value <> "" Then
WorksheetName = cell.Offset(0, -1).Value
Set shW = WBOR.Sheets.Add(After:=Sheets(Sheets.count))
shW.Name = WorksheetName
Set shMJ = Wmjf.ActiveSheet
shMJ.Range("A:U").AutoFilter field:=12, Criteria1:="*" & cell.Value 'Filters depending on the cell value
Set AutoFilterRng = shMJ.AutoFilter.Range.Offset(1, 0).Resize(.Rows.count - 1, 1).SpecialCells(xlCellTypeVisible)
shMJ.AutoFilter.Range.Offset(1, 0).Resize(shMJ.AutoFilter.Range.count - 1).Copy shW.Range("A1")
shMJ.AutoFilterMode = False
End If
Next
This is not the answer BUT may help you:
Sub test()
Dim shtName As String
With ThisWorkbook
'Let assume that the sheet name we want appears in Sheet3, range A1
'Get sheet name
shtName = .Worksheets("Sheet3").Range("A1").Value
'Activate sheet with name shtName
.Worksheets(shtName).Activate
End With
End Sub
I should not use .paste instead it should be .PasteSpecial and set the Worksheet. In this case WorksheetName = Cell.Offset(0,-1).Value and then set the Worksheet with that name so it will be Dim CurrentWSName, Set CurrentWSName = ActiveWorkbook.Sheets(WorksheetName) Code will be like this:
Dim AutoFilterRng As Range
Dim WorksheetName As String
Dim CurrentWSName As Worksheet
For Each Cell In Range("H5", Range("H5").End(xlDown))
If Cell.Value <> "" Then
WorksheetName = Cell.Offset(0, -1).Value
Set CurrentWSName = ActiveWorkbook.Sheets(WorksheetName)
Workbooks.Open MJFile
ActiveSheet.Range("A:U").AutoFilter Field:=12, Criteria1:="*" & Cell.Value
With ActiveSheet.AutoFilter.Range
Set AutoFilterRng = .Offset(1, 0).Resize(.Rows.Count - 1, 1).SpecialCells(xlCellTypeVisible)
End With
ActiveSheet.AutoFilter.Range.Offset(1, 0).Resize(ActiveSheet.AutoFilter.Range.Count - 1).Copy
Workbooks.Open WBOR
CurrentWSName.Activate
Range("A1").PasteSpecial
Workbooks.Open MJFile
AutoFilterMode = False
Workbooks.Open WBOR
End If
Next
Related
How to select and copy data up to the searched value?
Can anyone please help me out, Im getting a little bit desperate I want to search for data and then select and copy every-row up to the searched point, however I wasnt able to do this all I can do is to copy the row that includes the searched data Sub Prehled() Dim datarng As Range Dim lr As Long Dim wb As Workbook Dim VysledekHledani As Long Dim Obdobi As String Application.ScreenUpdating = False ThisWorkbook.Activate Range("A1").Select Obdobi = Sheets("IN7").Range("Kvartal").Value Sheets("PomocnyList_3").Select Sheets("PomocnyList_3").AutoFilterMode = False lr = Sheets("PomocnyList_3").Range("A" & Rows.Count).End(xlUp).Row Set datarng = ActiveSheet.Range("$A$1:$AZ$" & lr) If Obdobi <> "" Then If en_likematch = True Then datarng.AutoFilter Field:=1, Criteria1:="=*" & Obdobi & "*", Operator:=xlAnd Else datarng.AutoFilter Field:=1, Criteria1:="=" & Obdobi End If End If VysledekHledani = Range("A1:A" & lr).SpecialCells(xlCellTypeVisible).Count If VysledekHledani > 1 Then Sheets("K_report").Select Cells.Range("B25").Value = "Test?" Application.CutCopyMode = False End If If VysledekHledani > 1 Then Sheets("PomocnyList_3").Select Range("A2:AZ99").SpecialCells(xlCellTypeVisible).Select ActiveSheet.AutoFilterMode = False Selection.Copy Sheets("K_report").Select Range("E25").PasteSpecial Paste:=xlPasteValues Application.CutCopyMode = False End If Application.ScreenUpdating = True End Sub
Using Application.Match(): Sub Prehled() Dim wsSrc As Worksheet, wb As Workbook, wsRpt As Worksheet Dim Obdobi As String, wc As String, m Set wb = ThisWorkbook 'best to be specific... Set wsSrc = wb.Worksheets("PomocnyList_3") Set wsRpt = wb.Worksheets("K_report") wsSrc.AutoFilterMode = False wc = IIf(en_likematch, "*", "") 'need wildcards? Obdobi = wb.Worksheets("IN7").Range("Kvartal").Value If Len(Obdobi) = 0 Then 'anything to search for? MsgBox "No search term entered", vbExclamation Exit Sub End If 'see if there's a match in ColA m = Application.Match(wc & Obdobi & wc, wsSrc.Columns("A"), 0) If Not IsError(m) Then 'if not an error then we got a match With wsSrc.Range("A2:AZ" & m) wb.Worksheets("K_report").Range("E25").Resize(.Rows.Count, .Columns.Count).Value = .Value End With End If End Sub
Optimize Excel VBA Macro for Copy-PasteValues
I'm new in Excel-VBA and I need to improve my macro performance. I have a macro that searches an excel, opens it, then goes through every sheet and copy-pastevalues for all cell with a specific color (yellow). Finally saves and closes the excel. In addition, excels sheets are locked and only those yellow cells are editable. This should be done for a list of excel that I indicate in a main template from where I call the macro. The problem is that it takes a lot of time and even gets blocked when the number of excels is more than 3. I paste my code below and hope anyone can help. Thanks! Sub Button1_Click() Application.ScreenUpdating = False Application.DisplayAlerts = False Dim filePath As String Dim rng As Range Dim cel As Range Dim cartera As String Dim plantilla As String Dim wb As Workbook Dim ws As Worksheet Dim obj_Cell As Range filePath = Application.ThisWorkbook.Path Range("B9").Select Set rng = Application.Range(Selection, Selection.End(xlDown)) For Each cel In rng.Cells cartera = cel.Value plantilla = cel.Offset(0, 1).Value If cartera = vbNullString Or plantilla = vbNullString Then GoTo Saltar End If Application.StatusBar = "Ejecutando Cartera: " & cartera & ", Plantilla: " & plantilla Set wb = Workbooks.Open(filePath & "\" & cartera & "\" & plantilla, UpdateLinks:=3) For Each ws In wb.Worksheets If ws.Name <> "Index" And ws.Name <> "Instructions" And ws.Name <> "Glossary" Then Worksheets(ws.Name).Activate For Each obj_Cell In Range("A1:DW105") With obj_Cell If obj_Cell.Interior.Color = RGB(255, 255, 153) Then obj_Cell.Select If obj_Cell.MergeCells = True Then obj_Cell.MergeArea.Select End If Selection.Copy Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=True, Transpose:=False If obj_Cell.MergeCells = True Then If obj_Cell.MergeArea(1).Value = vbNullString Then obj_Cell.MergeArea.Cells(1, 1).Select Selection.ClearContents End If Else If obj_Cell.Value = vbNullString Then obj_Cell.ClearContents End If End If End If End With Next obj_Cell Range("A1").Select End If Next ws Sheets(1).Select wb.Close SaveChanges:=True Saltar: Next cel Application.ScreenUpdating = True Application.DisplayAlerts = True Application.StatusBar = False End Sub
Untested- just some "start" ideas for you to use (e.g. no selections, using arrays, fix With statement, no GoTo). I don't understand the logic behind clearing vbNullstring. If it is necessary adapt the code in your way. I would also suggest opening files with displayalerts on because of few potential problems (e.g. "serious error occur last time file was opened" would hangs your macro) Sub Button1_Click() With Application .ScreenUpdating = False .StatusBar = True End With ' If possible change this reference ' from active sheet to sheet's name/codename/index Dim activeWs As Worksheet Set activeWs = ActiveSheet Dim filePath As String filePath = Application.ThisWorkbook.Path Dim wb As Workbook Dim ws As Worksheet Dim obj_Cell As Range ' range definition ' if lastRow not working change to yours xlDown ' if possible End(xlUp) method is more reliable Dim rng As Range Dim lastRw As Long With activeWs lastRw = .Cells(.Cells.Rows.Count, "B").End(xlUp).Row Set rng = .Range("B9:B" & lastRw) End With ' read whole ranges at once ' instead of offset it is possible also to read ' cartera and plantilla at the same time to 2Darray Dim cartera As Variant cartera = Application.Transpose(rng.Value2) Dim plantilla As Variant plantilla = Application.Transpose(rng.Offset(, 1).Value2) ' main loop Dim i As Long For i = 1 To UBound(cartera) If cartera(i) <> vbNullString Or plantilla(i) <> vbNullString Then Application.StatusBar = "Ejecutando Cartera: " & cartera(i) & ", Plantilla: " & plantilla(i) Set wb = Workbooks.Open(filePath & "\" & cartera(i) & "\" & plantilla(i), UpdateLinks:=3) For Each ws In wb.Worksheets If ws.Name <> "Index" And ws.Name <> "Instructions" And ws.Name <> "Glossary" Then For Each obj_Cell In ws.Range("A1:DW105") With obj_Cell If .Interior.Color = RGB(255, 255, 153) Then .Value2 = .Value2 ' I commented this part beacuse it does not make sense for me... ' If .MergeCells Then ' If .MergeArea(1).Value = vbNullString Then _ .MergeArea.Cells(1, 1).ClearContents ' Else ' If .Value = vbNullString Then .ClearContents ' End If End If End With Next obj_Cell End If Next ws ' I would place diplayalerts off here because of potential problems ' with opening files ' if problem occurs it can macro hangs Application.DisplayAlerts = False wb.Close SaveChanges:=True Application.DisplayAlerts = True End If Next i With Application .ScreenUpdating = True .DisplayAlerts = True .StatusBar = False End With End Sub
Copy Data from Workbooks Sheet1 to Master Sheet
I have macro, which copies data from selected workbooks' Sheet1 to this main workbook's Sheet1 in last row. For small number of files, it is fast, but when I select more files (say 20), it breaks and excel even crashes. How to make this more efficient as I am already using Application.EnableEvents and ScreenUpdating? Sub Copy_From_Workbooks() Dim numberOfFilesChosen, i As Integer Dim tempFileDialog As FileDialog Dim sourceWorkbook As Workbook Dim loLastRow As Long Application.EnableEvents = False Application.ScreenUpdating = False Set tempFileDialog = Application.FileDialog(msoFileDialogFilePicker) tempFileDialog.Filters.Add "Excel Files", "*.xlsx?", 1 tempFileDialog.AllowMultiSelect = True numberOfFilesChosen = tempFileDialog.Show For i = 1 To tempFileDialog.SelectedItems.Count Workbooks.Open tempFileDialog.SelectedItems(i) Set sourceWorkbook = ActiveWorkbook If ActiveWorkbook.Worksheets(1).Range("A1") <> "" Then With ActiveWorkbook.Worksheets(1) With .Cells(1).CurrentRegion .Offset(1).Resize(.Rows.Count - 1, .Columns.Count - 1).Copy End With End With End If With ThisWorkbook.Worksheets("Sheet1") loLastRow = .Cells(Rows.Count, 1).End(xlUp).Row + 1 .Range("A" & loLastRow).PasteSpecial Paste:=xlPasteValues Application.CutCopyMode = False 'ThisWorkbook.Save End With sourceWorkbook.Close Next i Application.EnableEvents = False Application.ScreenUpdating = True End Sub
You set a variable for the source workbook, but do not use it. Use With blocks so you don't call the referencing object over and over and over. Write the values directly as opposed to using the slower copy/paste. For i = 1 To tempFileDialog.SelectedItems.Count Set sourceWorkbook = Workbooks.Open(tempFileDialog.SelectedItems(i)) With sourceWorkbook.Worksheets(1) If .Range("A1") <> "" Then Dim valRange as Range With .Cells(1).CurrentRegion Set valRange = .Offset(1).Resize(.Rows.Count - 1, .Columns.Count - 1) End With End With End If With ThisWorkbook.Worksheets("Sheet1") loLastRow = .Cells(Rows.Count, 1).End(xlUp).Row + 1 .Range("A" & loLastRow).Resize(valRange.Rows.Count,valRange.Columns.Count).Value = valRange.Value 'ThisWorkbook.Save End With sourceWorkbook.Close Next i
Is there a simpler way of moving a lot of data
Basically i am making a program that will find all of the players from different teams and move them to their own workbook. There is 12 age groups and 4 divisions per age group (AE, A, AA and AAA). The code below works for one team (Minor Novice AE). I was wondering if there is a way for me to sort all of these without having to re write the same code 48 times. Thanks :) Sub Team() Dim rw As Long, lastrow As Long, MySel As Range 'Grabs skus and moves to new sheet With Worksheets("Sheet1") For rw = 1000 To 2 Step -1 If .Cells(rw, 2).Value Like "*Minor Novice*" And .Cells(rw, 3).Value Like ("AE") Then If MySel Is Nothing Then Set MySel = .Cells(rw, 1).EntireRow Workbooks.Open Filename:="C:\CODE\Team Lists\11 Minor Novice AE.xlsx" Else Set MySel = Union(MySel, .Cells(rw, 1).EntireRow) End If End If Next rw End With With ThisWorkbook.Worksheets("M Novice AE") lastrow = .Cells(.Rows.Count, 1).End(xlUp).Row If Not MySel Is Nothing Then MySel.Copy Destination:=.Cells(lastrow + 1, 1) 'MySel.Delete End If End With Dim Rng As Range Set Rng = ThisWorkbook.Worksheets("M Novice AE").Range("A1:AY300") Rng.Copy Dim s11 As Workbook Set s11 = Workbooks("11 Minor Novice AE") Dim last As Long Dim Rngnew As Range With s11.Sheets("Sheet1") If Application.WorksheetFunction.CountA(.Cells) <> 0 Then last = .Range("A65000").End(xlUp).Offset(1, 0).Row Else last = 1 End If End With Set Rngnew = s11.Worksheets("Sheet1").Range("A" & last) Rngnew.PasteSpecial End Sub
This will generically split a list onto separate sheets based on the contents of columns B and C - from there you can export each sheet as a separate workbook Sub SplitIntoSheets() dim r as range set r = range("a1") r.parent.usedrange.sort key1:=range("B1"),key2:=range("2c1"),hasheader:=true 'sort by age,division dim oldname as string Do 'start loop if r.offset(0,1)&r.offset(0,2)<>oldstring then 'need new sheet oldstring = r.offset(0,1)&r.offset(0,2) 'store new string AddSheet oldstring, r.parent end if r.entirerow.copy sheets(oldstring).range( rows.count,1).end(xlup).offset(1,0) 'copy row set r = r.offset(1,0) loop until r = "" end sub Sub AddSheet(s as string,source as worksheet) thisworkbook.worksheets.add activesheet.name = s source.rows(1).copy range("a1") 'copy titlw row from source sheet to new sheet end sub Not at computer, can't test this, there may be typos, it assumes a single sheet to begin with.
Create a new workbook for every unique value: Sub Copy_To_Workbooks() 'Note: This macro use the function LastRow Dim My_Range As Range Dim FieldNum As Long Dim FileExtStr As String Dim FileFormatNum As Long Dim CalcMode As Long Dim ViewMode As Long Dim ws2 As Worksheet Dim MyPath As String Dim foldername As String 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("A1:D" & 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 workbook" 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 = 1 'Turn off AutoFilter My_Range.Parent.AutoFilterMode = False 'Set the file extension/format If Val(Application.Version) < 12 Then 'You use Excel 97-2003 FileExtStr = ".xls": FileFormatNum = -4143 Else 'You use Excel 2007-2013 If ActiveWorkbook.FileFormat = 56 Then FileExtStr = ".xls": FileFormatNum = 56 Else FileExtStr = ".xlsx": FileFormatNum = 51 End If 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 'Delete the sheet RDBLogSheet if it exists On Error Resume Next Application.DisplayAlerts = False Sheets("RDBLogSheet").Delete Application.DisplayAlerts = True On Error GoTo 0 ' Add worksheet to copy/Paste the unique list Set ws2 = Worksheets.Add(After:=Sheets(Sheets.Count)) ws2.Name = "RDBLogSheet" 'Fill in the path\folder where you want the new folder with the files 'you can use also this "C:\Users\Ron\test" MyPath = Application.DefaultFilePath 'Add a slash at the end if the user forget it If Right(MyPath, 1) <> "\" Then MyPath = MyPath & "\" End If 'Create folder for the new files foldername = MyPath & Format(Now, "yyyy-mm-dd hh-mm-ss") & "\" MkDir foldername With ws2 'first we copy the Unique data from the filter field to ws2 My_Range.Columns(FieldNum).AdvancedFilter _ Action:=xlFilterCopy, _ CopyToRange:=.Range("A3"), 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("A4: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 new workbook with one sheet Set WSNew = Workbooks.Add(xlWBATWorksheet).Worksheets(1) 'Copy/paste the visible data to the new workbook 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 'Save the file in the new folder and close it On Error Resume Next WSNew.Parent.SaveAs foldername & _ cell.Value & FileExtStr, FileFormatNum If Err.Number > 0 Then Err.Clear ErrNum = ErrNum + 1 WSNew.Parent.SaveAs foldername & _ "Error_" & Format(ErrNum, "0000") & FileExtStr, FileFormatNum .Cells(cell.Row, "B").Formula = "=Hyperlink(""" & foldername & _ "Error_" & Format(ErrNum, "0000") & FileExtStr & """)" .Cells(cell.Row, "A").Interior.Color = vbRed Else .Cells(cell.Row, "B").Formula = _ "=Hyperlink(""" & foldername & cell.Value & FileExtStr & """)" End If WSNew.Parent.Close False On Error GoTo 0 End If 'Show all the data in the range My_Range.AutoFilter Field:=FieldNum Next cell .Cells(1, "A").Value = "Red cell: can't use the Unique name as file name" .Cells(1, "B").Value = "Created Files (Click on the link to open a file)" .Cells(3, "A").Value = "Unique Values" .Cells(3, "B").Value = "Full Path and File name" .Cells(3, "A").Font.Bold = True .Cells(3, "B").Font.Bold = True .Columns("A:B").AutoFit 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 ws2.Select 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 https://www.rondebruin.nl/win/s3/win006_3.htm
If autofilter gives no data move to next file
I have a code to copy the filtered data and paste. But it throws an error if there are blanks.Kindly help me on this. This is my code. Getting an error when there are blanks for filtered criteria. Kindly suggest me what needs to be added to ignore the error and go to next file Sub GetSheets() Dim shtname As String Dim Path As String Dim Filename As String Dim myRange As Range Dim NumRows As Long Path = ThisWorkbook.Sheets("Filepath").Range("B2").Value shtname = ThisWorkbook.Sheets("Filepath").Range("B3").Value Filename = Dir(Path & "*.xls") Do While Filename <> "" Workbooks.Open Filename:=Path & Filename, ReadOnly:=True Sheets(shtname).Select Columns("A:U").EntireColumn.Hidden = False Set myRange = ActiveSheet.Range("A:A") NumRows = Application.Count(myRange) r = Application.WorksheetFunction.CountA(Sheets(shtname).Range("A:A")) ActiveSheet.Range("$A$1:$U$1").AutoFilter Field:=19, Criteria1:="D.C" ActiveSheet.Range("A2:U" & NumRows).SpecialCells(xlCellTypeVisible).Select Selection.Copy Windows("Combined - Dc Pharmacy chargeback.xlsm").Activate Sheets("Sheet1").Select Range("A1").Select Selection.End(xlDown).Select ActiveCell.Offset(1, 0).Select ActiveSheet.Paste Application.CutCopyMode = False Application.DisplayAlerts = False Workbooks(Filename).Close Filename = Dir() Loop End Sub Kindly suggest on this
An error will occur when no cells are visible. You can trap this error with On Error Resume Next as shown below. Private Sub CopyFiltered() Dim Rng As Range Dim Rl As Long ' last row Application.ScreenUpdating = False With ActiveSheet Rl = .Cells(.Rows.Count, "A").End(xlUp).Row Set Rng = Range(.Cells(2, "A"), .Cells(Rl, "A")) .Range("$A$1:$U$1").AutoFilter Field:=19, Criteria1:="D.C" On Error Resume Next Set Rng = Rng.SpecialCells(xlCellTypeVisible) If Err = 0 Then Rng.Copy ' Change this address as required Worksheets("Manager").Cells(20, 3).Resize(Rng.Cells.Count, 1).PasteSpecial xlValues End If On Error GoTo 0 .ShowAllData Rng.AutoFilter End With With Application .ScreenUpdating = True .CutCopyMode = False End With End Sub
Sub GetSheets() Dim shtname As String Dim Path As String Dim Filename As String Dim myRange As Range Dim NumRows As Long Path = ThisWorkbook.Sheets("Filepath").Range("B2").Value shtname = ThisWorkbook.Sheets("Filepath").Range("B3").Value Filename = Dir(Path & "*.xls") On Error Resume Next Do While Filename <> "" Workbooks.Open Filename:=Path & Filename, ReadOnly:=True Sheets(shtname).Select Columns("A:U").EntireColumn.Hidden = False Set myRange = ActiveSheet.Range("A:A") NumRows = Application.Count(myRange) r = Application.WorksheetFunction.CountA(Sheets(shtname).Range("A:A")) ActiveSheet.Range("$A$1:$U$1").AutoFilter Field:=19, Criteria1:="D.C" ActiveSheet.Range("A2:U" & NumRows).SpecialCells(xlCellTypeVisible).Select x = ActiveSheet.Range("A65000").End(xlUp).Row If x > 1 Then Selection.Copy Windows("Combined - Dc Pharmacy chargeback.xlsm").Activate Sheets("Sheet1").Select Range("A1").Select Selection.End(xlDown).Select ActiveCell.Offset(1, 0).Select ActiveSheet.Paste End If Application.CutCopyMode = False Application.DisplayAlerts = False Workbooks(Filename).Close Filename = Dir() Loop End Sub