◆2行づつソートする
2行づつソートしたいと思ったことありませんか。
たとえばこんな表です。
かっこいい方法は知りません。
以下は 2行づつのソートを力づくでやってみたサンプル です。
選択されている表を自動判断して、2行ソートします。
コメントに何をやっているのか詳しく記入しました。
ダウンロードしたサンプル を動作させて、内容を理解してください。
Sub Sort()
Dim Book_Name As String
Dim Sheet_Name As String
Dim SelectArea As Range
Dim SelectAddress As String
Dim StartRow, StartColumn, MaxRow, MaxColumn As Integer
Dim Current_MaxRow As Integer
Dim i As Integer
Dim FoundCell As Range
Dim CopySource As Range
Dim PasteDist As Range
Book_Name = ActiveWorkbook.Name
Sheet_Name = ActiveSheet.Name
Set SelectArea = Selection
SelectAddress = SelectArea.Address
StartRow = SelectArea.Cells(1).Row
StartColumn = SelectArea.Cells.Column
MaxRow = SelectArea.Cells(SelectArea.Count).Row
MaxColumn = SelectArea.Cells(SelectArea.Count).Column
Range(Columns(StartColumn), Columns(StartColumn + 1)).Insert
For i = StartRow + 1 To MaxRow Step 2
Cells(i, StartColumn) = Cells(i, StartColumn + 2) & Format(i)
Cells(i + 1, StartColumn) = Cells(i, StartColumn + 2) & Format(i)
Cells(i, StartColumn + 1) = Cells(i, StartColumn + 2)
Next
Range(Cells(StartRow, StartColumn), Cells(MaxRow, MaxColumn + 2)).Select
Selection.Sort Key1:=Cells(StartRow + 1, StartColumn + 1), _
Order1:=xlAscending, Header:=xlYes, OrderCustom:=1, MatchCase:=False, _
Orientation:=xlTopToBottom, SortMethod:=xlPinYin
For i = (MaxRow + StartRow) / 2 + 1 To StartRow + 2 Step -1
Rows(i).Insert Shift:=xlDown
Next
Columns(StartColumn).NumberFormatLocal = "@"
Current_MaxRow = EffectiveRow_AssingColum_No(StartColumn)
For i = MaxRow + 1 To Current_MaxRow
Set CopySource = _
Range(Cells(i, StartColumn), Cells(i, MaxColumn + 2))
Set FoundCell = Range(Cells(StartRow, StartColumn), _
Cells(MaxRow, StartColumn)).Find(Cells(i, StartColumn))
If FoundCell Is Nothing Then
Else
Set PasteDist = _
Range(Cells(FoundCell.Row + 1, StartColumn), _
Cells(FoundCell.Row + 1, MaxColumn + 2))
PasteDist.Value = CopySource.Value
End If
Next
'++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Range(Columns(StartColumn), Columns(StartColumn + 1)).Delete
Range(Rows(MaxRow + 1), Rows(Current_MaxRow)).Delete
For i = StartRow + 1 To MaxRow Step 2
Range(Cells(i, StartColumn), Cells(i, MaxColumn)). _
Borders(xlEdgeBottom).LineStyle = xlNone
With Range(Cells(i + 1, StartColumn), _
Cells(1 + 1, MaxColumn)).Borders(xlEdgeBottom)
.LineStyle = xlContinuous
.Weight = xlMedium
.ColorIndex = xlAutomatic
End With
Next
Range("A1").Select
End Sub
Function EffectiveRow_AssingColum_No(col)
EffectiveRow_AssingColum_No = Cells(65536, col).End(xlUp).Row
End Function