I have some data that will always be 8 columns (A-H) the number of rows could be different every time (Dynamic).
If the string in column A ends with:
"IT", "LN" or "SJ" then the row value in Column G needs to be divided by 100.
If the string ends in "KK" the value in Column G needs to be
divided by 1000.
Otherwise no math operation to the row needs to be performed.
The data also needs to be sorted alphabetically by column C then by column H.
After this is done the header row (1). Can be deleted.
What I have so far "works" but it results in a very long list of 0.0000 values in column G that makes copying out the cleaned data difficult.
Would anyone be able to show me a more efficient solution?
Sub Clean()
Dim wkb As Workbook
Set wkb = ActiveWorkbook
Dim ws As Worksheet
Set ws = ActiveSheet
Range("A1").Select
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlDown)).Select
ws.Sort.SortFields.Clear
ws.Sort.SortFields.Add2 Key:=Range("H2:H2500" _
), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With ws.Sort
.SetRange Range("A1:H2500")
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
Range("I2").Select
ActiveCell.FormulaR1C1 = _
"=IF(OR(RIGHT(RC[-8],2) = ""SJ"", RIGHT(RC[-8],2) = ""LN"", RIGHT(RC[-8],2) = ""IT"", RIGHT(RC[-8],2) = ""KK""),IF(RIGHT(RC[-8],2) = ""KK"",RC[-2]/1000,RC[-2]/100),RC[-2])"
Range("I2").Select
Selection.Copy
Selection.End(xlToLeft).Select
Selection.End(xlDown).Select
Range("I2500").Select
Range(Selection, Selection.End(xlUp)).Select
Range("I3:I2500").Select
Range("I2500").Activate
ActiveSheet.Paste
Selection.End(xlUp).Select
Range(Selection, Selection.End(xlDown)).Select
Application.CutCopyMode = False
Selection.Copy
Range("G2").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Selection.NumberFormat = "0.0000"
Columns("I").Delete
Dim strDataRange As Range
Dim keyRange As Range
Set strDataRange = Range("A:H")
Set keyRange = Range("C1")
strDataRange.Sort Key1:=keyRange, Header:=xlYes
Rows(1).Delete
End sub
Sample Input Data
Codes
Population
Animal
Type
Size
Housing Qty
Average Cost
Country
SHIB IT
4,504
DOGE
Standard
SMALL
15,019
9.5557
JP
CORG LN
33,052
DOGE
Standard
SMALL
8,816
31,404.9100
FR
SOG SJ
1,417
CAT
Standard
BIG
90
247.2508
ZM
CHOW KK
873
DOGE
Standard
BIG
9,192
177.2797
CN
FLOP AG
991
CAT
Standard
BIG
7
597.0650
BZ
Desired Output Data:
Please, try the next compact and fast code. It will place the range to be processed in an array and drop down the processed result at the end. Now it returns overwriting the existing range. It can be easily adapted to return in another sheet:
Sub processRangeAH()
Dim sh As Worksheet, lastR As Long, rng As Range, arr, i As Long
Set sh = ActiveSheet
lastR = sh.Range("A" & sh.rows.count).End(xlUp).row
Set rng = sh.Range("A1:H" & lastR)
rng.Sort Key1:=sh.Range("H1"), Order1:=xlAscending, Header:=xlYes
arr = rng.Value2
For i = 2 To UBound(arr)
Select Case UCase(Right(arr(i, 1), 2))
Case "IT", "LN", "SJ": arr(i, 7) = arr(i, 7) / 100
Case "KK": arr(i, 7) = arr(i, 7) / 1000
End Select
Next i
rng.Value2 = arr
rng.Sort Key1:=sh.Range("C1"), Order1:=xlAscending, Header:=xlYes
sh.Range("G2:G" & lastR).NumberFormat = "0.0000"
sh.rows(1).Delete
End Sub
I posted this answer some hours before, when I left my office, but by mistake, in another thread...
Just to see how an array can be used, in order to increase the speed for larger range.
Try this. It copies everything to a new sheet so you don't lose the original data. Could be sped up if you have lots of data.
Sub x()
Dim ws As Worksheet, r As Long
Set ws = Worksheets.Add
Sheet1.Range("A1").CurrentRegion.Copy ws.Range("A1") 'assumes data on sheet1 (code name, change to suit)
For r = 2 To ws.Range("A" & Rows.Count).End(xlUp).Row
Select Case Right(ws.Cells(r, 1), 2)
Case "IT", "LN", "SJ": ws.Cells(r, "G").Value = ws.Cells(r, "G").Value / 100
Case "KK": ws.Cells(r, "G").Value = ws.Cells(r, "G").Value / 1000
End Select
Next r
With ws.Sort
.SortFields.Clear
.SortFields.Add2 Key:=ws.Range("C2:C" & ws.Range("A" & Rows.Count).End(xlUp).Row), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
.SortFields.Add2 Key:=Range("H2:H" & ws.Range("A" & Rows.Count).End(xlUp).Row), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
.SetRange Range("A1:H" & ws.Range("A" & Rows.Count).End(xlUp).Row)
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
End Sub
With below code I could sort data (marked with blue background) from 2 columns based on "B" column. Similarly I want to repeat the same for each blue block. I've highlighted cells manually just for illustration. Any help will be appreciated.
Code:
Sub SortRanges()
Dim firstcell As String
With Columns("B")
.Find(what:="*", after:=.Cells(1, 1), LookIn:=xlValues).Activate
firstcell = ActiveCell.Row
End With
Range(Selection, Selection.End(xlDown)).Select
Range(Selection, Selection.End(xlToLeft)).Select
ActiveWorkbook.Worksheets("Sheet4").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("Sheet4").Sort.SortFields.Add Key:=Range("B" & firstcell & ":B" & firstcell + 5), _
SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("Sheet4").Sort
.SetRange Range("A" & firstcell & ":B" & firstcell + 5)
.Header = xlGuess
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
End Sub
Try a loop down your column and, as it looks like everything is blocks of 5, do something like:
lr = cells(rows.count,1).end(xlup).row
For i = 1 to lr
if cells(i,1).interior.color = Blue Then `FIX THIS TO MATCH THE BLUE YOU WANT
Range(Cells(i,1),Cells(i+5,2)).Sort key1:=Range(Cells(i,2),Cells(i+5,2)), order1:=xlAscending, Header:=xlNo
i=i+5
End if
next i
I may have not understood the part about your highlighting... if that blue is the "highlight" then you can modify the above such that:
lr = cells(rows.count,1).end(xlup).row
For i = 1 to lr
if not isempty(cells(i,2)) Then
Range(Cells(i,1),Cells(i+5,2)).Sort key1:=Range(Cells(i,2),Cells(i+5,2)), order1:=xlAscending, Header:=xlNo
i=i+5
End if
next i
One more thing... if you can just run 2 sorts in sequence, second should be your final sort, like:
lr = cells(rows.count,1).end(xlup).row
For i = 1 to lr
if not isempty(cells(i,2)) Then
Range(Cells(i,1),Cells(i+5,2)).Sort key1:=Range(Cells(i,1),Cells(i+5,1)), order1:=xlAscending, Header:=xlNo
Range(Cells(i,1),Cells(i+5,2)).Sort key1:=Range(Cells(i,2),Cells(i+5,2)), order1:=xlAscending, Header:=xlNo
i=i+5
End if
next i
I'm trying to clean up a bit of code and I was hoping SO could come to my rescue once again. I need to copy a range, open a new workbook with only one tab called "project code - Labels" (project code found in labels sheet cell A2 or A2 of new workbook). After pasting values and source formatting, I'd like to propmt the user to choose a save location, save the new file, close new workbook and return to the original workbook.
I have added comments for what I'd like to do in the code below
Sub GenLabels()
Application.ScreenUpdating = False
Worksheets("HR-Cal").Activate
Range("u100000").End(xlUp).Select
Range("ap2") = ActiveCell.Row
Worksheets("Labels").Activate
Dim rng As Range
Dim lab As String
Rows("3:" & Range("as1")).Select
Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Range("A2:AP2").AutoFill Destination:=Range("A2:AP" & Range("as1")), Type:=xlFillDefault
Range("A2:AP32").End(xlDown).Select
Range("a100000").End(xlUp).Activate
Range("at1") = ActiveCell.Row
lab = ("A2:AP" & Range("at1"))
Set rng = Range(lab)
rng.Select
ActiveWorkbook.Worksheets("Labels").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("Labels").Sort.SortFields.Add Key:=Range("X2:X" & Range("at1")) _
, SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("Labels").Sort
.SetRange Range("a1:ap" & Range("at1"))
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
For lrow = Cells(Cells.Rows.Count, "X").End(xlUp).Row To 1 Step -1
If Cells(lrow, "X") = 0 Then
Rows(lrow).EntireRow.Delete
End If
Next lrow
For lrow = Cells(Cells.Rows.Count, "D").End(xlUp).Row To 1 Step -1
If Cells(lrow, "D") = 0 Then
Rows(lrow).EntireRow.Delete
End If
Next lrow
Range("A1:AP1").End(xlDown).Copy
Application.ScreenUpdating = True
' msgbox that allows user to check filtered data and only runs the rest of the macro
' if they click OK
msgbox("If Label data looks correct please press OK to continue, or CANCEL to stop",vbOKCancel)
If vbCancel Then
End Sub
Else
'Code to paste only values and formatting into new workbook
Worksheets("Labels").Activate
Range("A1:AP1").End(xlDown).Copy
Sheets("Labels").Select
' create new workbook with only one sheet
Workbooks.Add
'paste label data
Selection.PasteSpecial Paste:=xlPasteAllUsingSourceTheme, Operation:=xlNone _
, SkipBlanks:=False, Transpose:=False
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Application.CutCopyMode = False
' prompt user to choose file save location, with file name PROJECT CODE - Labels
ActiveWorkbook.SaveAs Filename:="v:\Users\lies\NotReal\J31 Labels.xlsx", _
FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
' save and close new workbook
'return to orginal workbook
Worksheets("Labels").Activate
Range("A2").Select
End Sub
After lots of hair pulling and desk punching I figure this out please see code. granted this may not be the most efficient way but its fairly fast and without errors
Sub GenLabels()
Application.ScreenUpdating = False
Worksheets("HR-Cal").Activate
Range("u100000").End(xlUp).Select
Range("ap2") = ActiveCell.Row
Worksheets("Labels").Activate
Dim rng As Range
Dim lab As String
Rows("3:" & Range("as1")).Select
Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Range("A2:AP2").Select
Selection.AutoFill Destination:=Range("A2:AP" & Range("as1")), Type:=xlFillDefault
Range("A2:AP32").End(xlDown).Select
Range("a100000").End(xlUp).Activate
Range("at1") = ActiveCell.Row
lab = ("A2:AP" & Range("at1"))
Set rng = Range(lab)
rng.Select
ActiveWorkbook.Worksheets("Labels").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("Labels").Sort.SortFields.Add Key:=Range("X2:X" & Range("at1")) _
, SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("Labels").Sort
.SetRange Range("a1:ap" & Range("at1"))
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
For lrow = Cells(Cells.Rows.Count, "X").End(xlUp).Row To 1 Step -1
If Cells(lrow, "X") = 0 Then
Rows(lrow).EntireRow.Delete
End If
Next lrow
For lrow = Cells(Cells.Rows.Count, "D").End(xlUp).Row To 1 Step -1
If Cells(lrow, "D") = 0 Then
Rows(lrow).EntireRow.Delete
End If
Next lrow
Dim last As String
Range("a100000").End(xlUp).Activate
last = ActiveCell.Row
Range("A1:AP" & last).Copy
'Application.ScreenUpdating = True
Sheets.Add After:=Sheets(Sheets.Count)
ActiveSheet.Name = ActiveSheet.Range("A2") & " " & Range("Z2") & " - Labels"
'Range("A1").Select
Selection.PasteSpecial Paste:=xlPasteAllUsingSourceTheme, Operation:=xlNone _
, SkipBlanks:=False, Transpose:=False
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Selection.Columns.AutoFit
ActiveWindow.Zoom = 80
Range("A1").Select
ActiveSheet.Select
Application.CutCopyMode = False
ActiveSheet.Move
'
ActiveSheet.Name = ActiveSheet.Range("A2") & " " & Range("Z2") & " - Labels"
Application.ScreenUpdating = True
Dim bFileSaveAs As Boolean
bFileSaveAs = Application.Dialogs(xlDialogSaveAs).Show
End Sub
I am trying to write an excel macro to combine columns in a spreadsheet.
Specifically, there are seven columns, each with unique headers, that repeat indefinitely.
I want to combine all of the columns with the same headers into one, leaving only seven columns with all of the data. I do not want to concatenate the columns, but rather have each new column's data added to the previous one at the bottom.
As you can see in the code below, I have frankensteined it with macros I recorded and macros I have found online, as well as some of my own code here and there. It's very ineloquent and lengthy, and I'm sure there's an easier solution.
Sub Pop()
'
' Pop Macro
'
Dim i As Integer
Dim ws As Worksheet
Dim from_lastcol As Long
Dim from_lastrow As Long
Dim to_lastrow As Long
Dim from_colndx As Long
Dim ws_from As Worksheet, ws_to As Worksheet
Dim iSheetCount
Application.ScreenUpdating = False
'Format
Application.ScreenUpdating = False
Rows("1:1").Select
Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Range("A1").Select
ActiveCell.FormulaR1C1 = "=R[1]C"
Range("B1").Select
ActiveCell.FormulaR1C1 = "=IF(OR(R[1]C=R[1]C[-1]),"""",R[1]C)"
Range("B1").Select
Selection.Copy
Range("C1").Select
ActiveSheet.Paste
Application.CutCopyMode = False
ActiveCell.FormulaR1C1 = "=IF(OR(R[1]C=R[1]C[-1],R[1]C=R[1]C[-2]),"""",R[1]C)"
Range("C1").Select
Selection.Copy
Range("D1").Select
ActiveSheet.Paste
Application.CutCopyMode = False
ActiveCell.FormulaR1C1 = _
"=IF(OR(R[1]C=R[1]C[-1],R[1]C=R[1]C[-2],R[1]C=R[1]C[-3]),"""",R[1]C)"
Range("D1").Select
Selection.Copy
Range("E1").Select
ActiveSheet.Paste
Application.CutCopyMode = False
ActiveCell.FormulaR1C1 = _
"=IF(OR(R[1]C=R[1]C[-1],R[1]C=R[1]C[-2],R[1]C=R[1]C[-3],R[1]C=R[1]C[-4]),"""",R[1]C)"
Range("E1").Select
Selection.Copy
Range("F1").Select
ActiveSheet.Paste
Application.CutCopyMode = False
ActiveCell.FormulaR1C1 = _
"=IF(OR(R[1]C=R[1]C[-1],R[1]C=R[1]C[-2],R[1]C=R[1]C[-3],R[1]C=B2F2=R[1]C[-5]),"""",R[1]C)"
Range("F1").Select
ActiveCell.FormulaR1C1 = _
"=IF(OR(R[1]C=R[1]C[-1],R[1]C=R[1]C[-2],R[1]C=R[1]C[-3],R[1]C=R[1]C[-4],R[1]C=R[1]C[-5]),"""",R[1]C)"
Range("F1").Select
Selection.Copy
Range("G1").Select
ActiveSheet.Paste
Application.CutCopyMode = False
ActiveCell.FormulaR1C1 = _
"=IF(OR(R[1]C=R[1]C[-1],R[1]C=R[1]C[-2],R[1]C=R[1]C[-3],R[1]C=R[1]C[-4],R[1]C=B2G2=R[1]C[-6]),"""",R[1]C)"
Range("G1").Select
ActiveCell.FormulaR1C1 = _
"=IF(OR(R[1]C=R[1]C[-1],R[1]C=R[1]C[-2],R[1]C=R[1]C[-3],R[1]C=R[1]C[-4],R[1]C=R[1]C[-5],R[1]C=R[1]C[-6]),"""",R[1]C)"
Range("G1").Select
Selection.Copy
Range("H1").Select
ActiveSheet.Paste
Application.CutCopyMode = False
ActiveCell.FormulaR1C1 = _
"=IF(OR(R[1]C=R[1]C[-1],R[1]C=R[1]C[-2],R[1]C=R[1]C[-3],R[1]C=R[1]C[-4],R[1]C=R[1]C[-5],R[1]C=R[1]C[-6],R[1]C=R[1]C[-7]),"""",R[1]C)"
Range("H1").Select
Selection.Copy
Range("I1").Select
ActiveSheet.Paste
Application.CutCopyMode = False
ActiveCell.FormulaR1C1 = _
"=IF(OR(R[1]C=R[1]C[-1],R[1]C=R[1]C[-2],R[1]C=R[1]C[-3],R[1]C=R[1]C[-4],R[1]C=R[1]C[-5],R[1]C=R[1]C[-6],R[1]C=R[1]C[-7],R[1]C=R[1]C[-8]),"""",R[1]C)"
Range("I1").Select
Selection.Copy
Range("J1").Select
ActiveSheet.Paste
Application.CutCopyMode = False
ActiveCell.FormulaR1C1 = _
"=IF(OR(R[1]C=R[1]C[-1],R[1]C=R[1]C[-2],R[1]C=R[1]C[-3],R[1]C=R[1]C[-4],R[1]C=R[1]C[-5],R[1]C=R[1]C[-6],R[1]C=R[1]C[-7],R[1]C=R[1]C[-8],R[1]C=R[1]C[-9]),"""",R[1]C)"
Rows("1:1").Select
Selection.Copy
Selection.PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:= _
False, Transpose:=False
Rows("1:1").Select
Application.CutCopyMode = False
Selection.Copy
Sheets.Add
Sheets("Sheet2").Select
Sheets.Add
Sheets("Sheet3").Select
Sheets.Add
Sheets("Sheet4").Select
Sheets.Add
Sheets("Sheet5").Select
Sheets.Add
Sheets("Sheet6").Select
Sheets.Add
Sheets("Sheet7").Select
Sheets.Add
Sheets("Sheet8").Select
Sheets.Add
Sheets("Sheet9").Select
Sheets.Add
Sheets("Sheet10").Select
Sheets.Add
Sheets("Sheet11").Select
Sheets("Sheet11").Name = "Legend"
ActiveSheet.Paste
ActiveWindow.SmallScroll ToRight:=-4
ActiveWindow.ScrollWorkbookTabs Sheets:=-1
ActiveWindow.ScrollWorkbookTabs Sheets:=-1
Sheets("Sheet1").Select
Rows("1:1").Select
Application.CutCopyMode = False
Selection.Delete Shift:=xlUp
Sheets("Sheet2").Select
'Format Sheet 2
Sheets("Sheet2").Select
Range("A1").Select
ActiveCell.FormulaR1C1 = "=IF(Sheet1!R1C=Legend!R1C1,Sheet1!RC,""P"")"
Range("A1").Select
Selection.AutoFill Destination:=Range("A1:A500"), Type:=xlFillDefault
Range("A1:A500").Select
Selection.AutoFill Destination:=Range("A1:ZZ500"), Type:=xlFillDefault
Range("A1:ZZ500").Select
Selection.Copy
Selection.PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:= _
False, Transpose:=False
Application.CutCopyMode = False
Selection.Replace what:="P", Replacement:="", lookat:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False
ActiveWorkbook.ActiveSheet.Sort.SortFields.Clear
ActiveWorkbook.ActiveSheet.Sort.SortFields.Add Key:=Range("A1:ZZ1") _
, SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:=xlSortNormal
With ActiveWorkbook.ActiveSheet.Sort
.SetRange Range("A1:ZZ500")
.header = xlNo
.MatchCase = False
.Orientation = xlLeftToRight
.SortMethod = xlPinYin
.Apply
End With
'Format Sheet 3
Sheets("Sheet3").Select
Range("A1").Select
ActiveCell.FormulaR1C1 = "=IF(Sheet1!R1C=Legend!R1C2,Sheet1!RC,""P"")"
Range("A1").Select
Selection.AutoFill Destination:=Range("A1:A500"), Type:=xlFillDefault
Range("A1:A500").Select
Selection.AutoFill Destination:=Range("A1:ZZ500"), Type:=xlFillDefault
Range("A1:ZZ500").Select
Selection.Copy
Selection.PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:= _
False, Transpose:=False
Application.CutCopyMode = False
Selection.Replace what:="P", Replacement:="", lookat:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False
ActiveWorkbook.ActiveSheet.Sort.SortFields.Clear
ActiveWorkbook.ActiveSheet.Sort.SortFields.Add Key:=Range("A1:ZZ1") _
, SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:=xlSortNormal
With ActiveWorkbook.ActiveSheet.Sort
.SetRange Range("A1:ZZ500")
.header = xlNo
.MatchCase = False
.Orientation = xlLeftToRight
.SortMethod = xlPinYin
.Apply
End With
'Format Sheet 4
Sheets("Sheet4").Select
Range("A1").Select
ActiveCell.FormulaR1C1 = "=IF(Sheet1!R1C=Legend!R1C3,Sheet1!RC,""P"")"
Range("A1").Select
Selection.AutoFill Destination:=Range("A1:A500"), Type:=xlFillDefault
Range("A1:A500").Select
Selection.AutoFill Destination:=Range("A1:ZZ500"), Type:=xlFillDefault
Range("A1:ZZ500").Select
Selection.Copy
Selection.PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:= _
False, Transpose:=False
Application.CutCopyMode = False
Selection.Replace what:="P", Replacement:="", lookat:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False
ActiveWorkbook.ActiveSheet.Sort.SortFields.Clear
ActiveWorkbook.ActiveSheet.Sort.SortFields.Add Key:=Range("A1:ZZ1") _
, SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:=xlSortNormal
With ActiveWorkbook.ActiveSheet.Sort
.SetRange Range("A1:ZZ500")
.header = xlNo
.MatchCase = False
.Orientation = xlLeftToRight
.SortMethod = xlPinYin
.Apply
End With
'Format Sheet 5
Sheets("Sheet5").Select
Range("A1").Select
ActiveCell.FormulaR1C1 = "=IF(Sheet1!R1C=Legend!R1C4,Sheet1!RC,""P"")"
Range("A1").Select
Selection.AutoFill Destination:=Range("A1:A500"), Type:=xlFillDefault
Range("A1:A500").Select
Selection.AutoFill Destination:=Range("A1:ZZ500"), Type:=xlFillDefault
Range("A1:ZZ500").Select
Selection.Copy
Selection.PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:= _
False, Transpose:=False
Application.CutCopyMode = False
Selection.Replace what:="P", Replacement:="", lookat:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False
ActiveWorkbook.ActiveSheet.Sort.SortFields.Clear
ActiveWorkbook.ActiveSheet.Sort.SortFields.Add Key:=Range("A1:ZZ1") _
, SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:=xlSortNormal
With ActiveWorkbook.ActiveSheet.Sort
.SetRange Range("A1:ZZ500")
.header = xlNo
.MatchCase = False
.Orientation = xlLeftToRight
.SortMethod = xlPinYin
.Apply
End With
'Format Sheet 6
Sheets("Sheet6").Select
Range("A1").Select
ActiveCell.FormulaR1C1 = "=IF(Sheet1!R1C=Legend!R1C5,Sheet1!RC,""P"")"
Range("A1").Select
Selection.AutoFill Destination:=Range("A1:A500"), Type:=xlFillDefault
Range("A1:A500").Select
Selection.AutoFill Destination:=Range("A1:ZZ500"), Type:=xlFillDefault
Range("A1:ZZ500").Select
Selection.Copy
Selection.PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:= _
False, Transpose:=False
Application.CutCopyMode = False
Selection.Replace what:="P", Replacement:="", lookat:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False
ActiveWorkbook.ActiveSheet.Sort.SortFields.Clear
ActiveWorkbook.ActiveSheet.Sort.SortFields.Add Key:=Range("A1:ZZ1") _
, SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:=xlSortNormal
With ActiveWorkbook.ActiveSheet.Sort
.SetRange Range("A1:ZZ500")
.header = xlNo
.MatchCase = False
.Orientation = xlLeftToRight
.SortMethod = xlPinYin
.Apply
End With
'Format Sheet 7
Sheets("Sheet7").Select
Range("A1").Select
ActiveCell.FormulaR1C1 = "=IF(Sheet1!R1C=Legend!R1C6,Sheet1!RC,""P"")"
Range("A1").Select
Selection.AutoFill Destination:=Range("A1:A500"), Type:=xlFillDefault
Range("A1:A500").Select
Selection.AutoFill Destination:=Range("A1:ZZ500"), Type:=xlFillDefault
Range("A1:ZZ500").Select
Selection.Copy
Selection.PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:= _
False, Transpose:=False
Application.CutCopyMode = False
Selection.Replace what:="P", Replacement:="", lookat:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False
ActiveWorkbook.ActiveSheet.Sort.SortFields.Clear
ActiveWorkbook.ActiveSheet.Sort.SortFields.Add Key:=Range("A1:ZZ1") _
, SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:=xlSortNormal
With ActiveWorkbook.ActiveSheet.Sort
.SetRange Range("A1:ZZ500")
.header = xlNo
.MatchCase = False
.Orientation = xlLeftToRight
.SortMethod = xlPinYin
.Apply
End With
'Format Sheet 8
Sheets("Sheet8").Select
Range("A1").Select
ActiveCell.FormulaR1C1 = "=IF(Sheet1!R1C=Legend!R1C7,Sheet1!RC,""P"")"
Range("A1").Select
Selection.AutoFill Destination:=Range("A1:A500"), Type:=xlFillDefault
Range("A1:A500").Select
Selection.AutoFill Destination:=Range("A1:ZZ500"), Type:=xlFillDefault
Range("A1:ZZ500").Select
Selection.Copy
Selection.PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:= _
False, Transpose:=False
Application.CutCopyMode = False
Selection.Replace what:="P", Replacement:="", lookat:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False
ActiveWorkbook.ActiveSheet.Sort.SortFields.Clear
ActiveWorkbook.ActiveSheet.Sort.SortFields.Add Key:=Range("A1:ZZ1") _
, SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:=xlSortNormal
With ActiveWorkbook.ActiveSheet.Sort
.SetRange Range("A1:ZZ500")
.header = xlNo
.MatchCase = False
.Orientation = xlLeftToRight
.SortMethod = xlPinYin
.Apply
End With
'Format Sheet 9
Sheets("Sheet9").Select
Range("A1").Select
ActiveCell.FormulaR1C1 = "=IF(Sheet1!R1C=Legend!R1C8,Sheet1!RC,""P"")"
Range("A1").Select
Selection.AutoFill Destination:=Range("A1:A500"), Type:=xlFillDefault
Range("A1:A500").Select
Selection.AutoFill Destination:=Range("A1:ZZ500"), Type:=xlFillDefault
Range("A1:ZZ500").Select
Selection.Copy
Selection.PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:= _
False, Transpose:=False
Application.CutCopyMode = False
Selection.Replace what:="P", Replacement:="", lookat:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False
ActiveWorkbook.ActiveSheet.Sort.SortFields.Clear
ActiveWorkbook.ActiveSheet.Sort.SortFields.Add Key:=Range("A1:ZZ1") _
, SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:=xlSortNormal
With ActiveWorkbook.ActiveSheet.Sort
.SetRange Range("A1:ZZ500")
.header = xlNo
.MatchCase = False
.Orientation = xlLeftToRight
.SortMethod = xlPinYin
.Apply
End With
'Format Sheet 10
Sheets("Sheet10").Select
Range("A1").Select
ActiveCell.FormulaR1C1 = "=IF(Sheet1!R1C=Legend!R1C9,Sheet1!RC,""P"")"
Range("A1").Select
Selection.AutoFill Destination:=Range("A1:A500"), Type:=xlFillDefault
Range("A1:A500").Select
Selection.AutoFill Destination:=Range("A1:ZZ500"), Type:=xlFillDefault
Range("A1:ZZ500").Select
Selection.Copy
Selection.PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:= _
False, Transpose:=False
Application.CutCopyMode = False
Selection.Replace what:="P", Replacement:="", lookat:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False
ActiveWorkbook.ActiveSheet.Sort.SortFields.Clear
ActiveWorkbook.ActiveSheet.Sort.SortFields.Add Key:=Range("A1:ZZ1") _
, SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:=xlSortNormal
With ActiveWorkbook.ActiveSheet.Sort
.SetRange Range("A1:ZZ500")
.header = xlNo
.MatchCase = False
.Orientation = xlLeftToRight
.SortMethod = xlPinYin
.Apply
End With
'Cycle
For i = 2 To 10
mysheet = "Sheet" & i
Sheets(mysheet).Select
On Error GoTo Error_Handler
'CollapseColumns
Set ws_from = ActiveWorkbook.ActiveSheet
Rows("1:1").Select
Selection.Delete Shift:=xlUp
from_lastcol = ws_from.Cells(1, Columns.Count).End(xlToLeft).Column
'Turn error checking off so if no "AllData" trying to delete doesn't generate Error
On Error Resume Next
'so not prompted to confirm delete
Application.DisplayAlerts = False
'Delete if already exists so don't get error
ActiveWorkbook.Worksheets("AllData").Delete
Application.DisplayAlerts = True
'turn error checking back on
On Error GoTo 0
'since you refer to "AllData" throughout
Set ws_to = Worksheets.Add
ws_to.Name = "AllData"
For from_colndx = 1 To from_lastcol
from_lastrow = ws_from.Cells(Rows.Count, from_colndx).End(xlUp).Row
'If you're going to exceed 65536 rows
If from_lastrow + ws_to.Cells(Rows.Count, 1).End(xlUp).Row <= 65536 Then
to_lastrow = ws_to.Cells(Rows.Count, 1).End(xlUp).Row
Else
GoTo Error_Handler
End If
ws_from.Range(ws_from.Cells(1, from_colndx), ws_from.Cells(from_lastrow, _
from_colndx)).Copy ws_to.Cells(to_lastrow + 1, 1)
Next
For iSheetCount = 1 To Sheets.Count
Sheets(iSheetCount).Name = iSheetCount
Next iSheetCount
' this deletes any blank rows
ws_to.Columns(1).SpecialCells(xlCellTypeBlanks).EntireRow.Delete
Next i
Error_Handler:
Sheets("Sheet2").Delete
Sheets("Sheet3").Delete
Sheets("Sheet4").Delete
Sheets("Sheet5").Delete
Sheets("Sheet6").Delete
Sheets("Sheet7").Delete
Sheets("Sheet8").Delete
Sheets("Sheet9").Delete
Sheets("Sheet10").Delete
Sheets("AllData").Delete
Application.ScreenUpdating = True
End Sub
First off, you should always avoid using Select, Selection, & ActiveCell as explained here. The macro recorder is a good place to start, so good job getting the macro to work!
I believe the following code will accomplish what you want to happen without having to add and delete sheets:
Option Explicit
Sub Test()
Dim ws As Worksheet
Dim FirstLastRow As Long
Dim curLastRow As Long
Dim LastColumn As Long
Dim i As Long, j As Long
Application.ScreenUpdating = False
Set ws = ThisWorkbook.Worksheets("Sheet1")
LastColumn = ws.Cells(1, Columns.Count).End(xlToLeft).Column
For i = 1 To LastColumn
FirstLastRow = ws.Cells(Rows.Count, i).End(xlUp).Row
For j = LastColumn To i + 1 Step -1
If ws.Cells(1, j).Value = ws.Cells(1, i).Value And i <> j Then
curLastRow = ws.Cells(Rows.Count, j).End(xlUp).Row
ws.Range(ws.Cells(2, j), ws.Cells(curLastRow, j)).Copy ws.Cells(FirstLastRow + 1, i)
ws.Columns(j).Delete Shift:=xlToLeft
FirstLastRow = ws.Cells(Rows.Count, i).End(xlUp).Row
End If
Next j
LastColumn = ws.Cells(1, Columns.Count).End(xlToLeft).Column
Next i
For i = 1 To LastColumn
curLastRow = ws.Cells(Rows.Count, i).End(xlUp).Row
With ws.Sort
.SortFields.Clear
.SortFields.Add Key:=ws.Range(ws.Cells(2, i), ws.Cells(curLastRow, i)), SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:=xlSortNormal
.SetRange ws.Range(ws.Cells(2, i), ws.Cells(curLastRow, i))
.Header = xlNo
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
Next i
Application.ScreenUpdating = True
End Sub
Notes:
You'll need to replace "Sheet1" with the correct sheet reference if it changes.
Option Explicit at the top forces you to dimension each variable before it is used. This helps eliminate issues in the future because all variables that you do not dimension are automatically dimensioned as Variant by Excel.
EDIT
Here's a different variation tailored specifically to your workbook (http://imgur.com/hGCoWHt) that does not rely on finding LastColumn:
Option Explicit
Sub Test2()
Dim ws As Worksheet
Dim FirstLastRow As Long
Dim curLastRow As Long
Dim i As Long
Application.ScreenUpdating = False
Set ws = ThisWorkbook.Worksheets("Sheet1")
Do Until ws.Cells(1, 8).Value = ""
For i = 7 To 1 Step -1
FirstLastRow = ws.Cells(Rows.Count, i).End(xlUp).Row
curLastRow = ws.Cells(Rows.Count, i + 7).End(xlUp).Row
ws.Range(ws.Cells(2, i + 7), ws.Cells(curLastRow, i + 7)).Copy ws.Cells(FirstLastRow + 1, i)
ws.Columns(i + 7).Delete
Next i
Loop
For i = 1 To 7
curLastRow = ws.Cells(Rows.Count, i).End(xlUp).Row
With ws.Sort
.SortFields.Clear
.SortFields.Add Key:=ws.Range(ws.Cells(2, i), ws.Cells(curLastRow, i)), SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:=xlSortNormal
.SetRange ws.Range(ws.Cells(2, i), ws.Cells(curLastRow, i))
.Header = xlNo
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
Next i
Application.ScreenUpdating = True
End Sub