I have a list of data that I'm copying from one sheet to another. Here is my list of data. My goal is to move Column A from Sheet 1 to Column B in Sheet 2 and sort the data from "a" to "b" to "c"...basically in alphabetical order. For example: Column A contains (a, a, a, b ,ca, b, d, a, b, a) and I want it to be arranged in Column B of Sheet 2 like this (a, a, a, a, a, a, b, b, b, c, d). Below is my code. Please help if you can.
Sub Button1_Click()
lastrow = Worksheets("Sheet1").Range("A" & Rows.Count).End(xlUp).Row
For i = 2 To lastrow
'Conditional if statement that copies "a's" in Sheet 1, Column A and pastes in Sheet 2, Column B
If Worksheets("Sheet1").Range("A" & i).Value = "a" Then
Worksheets("Sheet1").Range("A" & i).Copy
Worksheets("Sheet2").Activate
lastRow2 = Worksheets("Sheet2").Range("A" & Rows.Count).End(xlUp).Row
Worksheets("Sheet2").Range("B" & i + 1).Select
ActiveSheet.Paste
'Worksheets("Sheet2").Range("B" & i + 1).Interior.Color = vbCyan
'Worksheets("Sheet2").Range("B" & i).Borders.Color = rbgBlack
End If
'Deletes empty cells and shifts "a's" upward
If Worksheets("Sheet2").Range("B" & i).Value = "" Then
Columns("B:B").Select
Selection.SpecialCells(xlCellTypeBlanks).Select
Selection.Delete Shift:=xlUp
End If
'Conditional if statement that copies data in Sheet 1, Column B and pastes in Sheet 2, Column C
If Worksheets("Sheet1").Range("A" & i).Value = "a" Then
Worksheets("Sheet1").Range("B" & i).Copy
Worksheets("Sheet2").Activate
lastRow2 = Worksheets("Sheet2").Range("A" & Rows.Count).End(xlUp).Row
Worksheets("Sheet2").Range("C" & i + 1).Select
ActiveSheet.Paste
End If
'Deletes empty cells and shifts data upward in Column C
If Worksheets("Sheet2").Range("A" & i).Value = "" Then
Columns("C:C").Select
Selection.SpecialCells(xlCellTypeBlanks).Select
Selection.Delete Shift:=xlUp
End If
Next i
End Sub
I believe you are complicating yourself too much. This should work:
lastrow = Worksheets("Sheet1").Range("A" & Rows.Count).End(xlUp).Row
Range("A2:A" & lastrow).Select
Selection.Cut
Sheets("Sheet2").Select
Range("B2").Select
ActiveSheet.Paste
ActiveWorkbook.Worksheets("Sheet2").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("Sheet2").Sort.SortFields.Add2 Key:=Range("B2:B" & lastrow) _
, SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("Sheet2").Sort
.SetRange Range("B2:B" & lastrow)
.Header = xlGuess
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
It takes ColumnA of Sheet1, cuts its contents and pastes them in ColumnB of Sheet2, before sorting them in alphabetical order.
Best, C.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.