| 
    
     |  | それでうまくいかない理由がわかりました。一番最後のデータの月を指定したとき、 空白セル範囲(MyR)の設定が、一つ不足してしまうことが原因でした。
 それで以下のように修正したところ、うまくいきました。
 
 Sub My集計()
 Dim Mth As Long, LstR As Long, Clc As Long
 Dim MyR As Range, C As Range
 Dim MyV As Variant
 Const Pmt As String = _
 "集計する月を1〜12の整数で入力して下さい"
 
 With Application
 Do
 Mth = .InputBox(Pmt, Type:=1)
 If Mth = False Then Exit Sub
 Loop While Mth < 1 Or Mth > 12
 .ScreenUpdating = False
 End With
 LstR = Range("A65536").End(xlUp).Row - 1
 With Range("IV1").End(xlToLeft).Offset(, 1)
 .Value = "月"
 With .Offset(1).Resize(LstR)
 .Formula = "=MONTH($A2)"
 .Value = .Value
 End With
 If IsError(Application.Match(Mth, .EntireColumn, 0)) Then
 MsgBox "指定した月のデータはありません", 48
 .EntireColumn.ClearContents: GoTo ELine
 End If
 End With
 With Sheets("Sheet2")
 .Range("A:A").ClearContents
 .Range("A1").Value = Mth & "月の集計"
 End With
 With Range("A1").CurrentRegion
 Clc = .Columns.Count
 .Sort Key1:=Range("IV1").End(xlToLeft), _
 Order1:=xlAscending, Key2:=Range("D1"), _
 Order2:=xlAscending, Header:=xlYes, _
 Orientation:=xlSortColumns
 .Subtotal 4, xlCount, Array(4)
 End With
 With Cells(65536, Clc).End(xlUp)
 If .Value = Mth Then
 Set MyR = Range(Cells(2, Clc), .Cells.Offset(1)) _
 .SpecialCells(4)
 Else
 Set MyR = Range(Cells(2, Clc), .Cells).SpecialCells(4)
 End If
 End With
 For Each C In MyR
 If C.Offset(-1).Value = Mth Then
 MyV = Array(Cells(C.Row - 1, 4).Value, _
 Cells(C.Row, 4).Value & " 件")
 Sheets("Sheet2").Range("A65536").End(xlUp).Offset(1) _
 .Resize(, 2).Value = MyV
 ElseIf C.Offset(-1).Value > Mth Then
 Exit For
 End If
 Next
 Set MyR = Nothing: Columns(Clc).ClearContents
 With Range("A1").CurrentRegion
 .RemoveSubtotal
 .Sort Key1:=Range("A1"), Order1:=xlAscending, _
 Header:=xlYes, Orientation:=xlSortColumns
 End With
 Sheets("Sheet2").Activate
 ELine:
 Application.ScreenUpdating = True
 End Sub
 
 |  |