プロが教えるわが家の防犯対策術!

VBA初心者です。
下記のようなコードを書いてB11~BH41をソートしたいのですが「オブジェクトが必要です」というエラーが出て上手く動いてくれません。
B11~BH41は横のセルと結合しているものがいくつか含まれているため一度結合を解除して再び結合させており、B11の列には日付、L11の列には時間を入れています。

Sub sort2keys()
Dim KeyCells As Range
Dim i As Integer
Dim x As Integer, y As Integer
x = Target.Column
y = Target.Row
Set KeyCells = Range("B11:B41")
If Not Application.Intersect(KeyCells, Range(Target.Address)) Is Nothing Then
'日付が消去された場合は行に入力されているものも消去 start
If Cells(y, 2).Value = "" Then
Application.ScreenUpdating = False
Range(Cells(y, 8), Cells(y, 21)).ClearContents
Range(Cells(y, 26), Cells(y, 35)).ClearContents
Range(Cells(y, 40), Cells(y, 60)).ClearContents
Application.ScreenUpdating = True
End If
'日付が消去された場合は行に入力されているものも消去 endS
ActiveSheet.Unprotect
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False
Range("B11:BH41").UnMerge
Range("B11:BH41").sort key1:=Range("B11"), order1:=xlAscending, Key2:=Range("L11"), Order2:=xlAscending

i = 11
While i < 42
Range(Cells(i, 2), Cells(i, 3)).Merge
Range(Cells(i, 4), Cells(i, 5)).Merge
Range(Cells(i, 6), Cells(i, 7)).Merge
Range(Cells(i, 8), Cells(i, 11)).Merge
Range(Cells(i, 12), Cells(i, 16)).Merge
Range(Cells(i, 17), Cells(i, 21)).Merge
Range(Cells(i, 22), Cells(i, 25)).Merge
Range(Cells(i, 26), Cells(i, 30)).Merge
Range(Cells(i, 31), Cells(i, 35)).Merge
Range(Cells(i, 36), Cells(i, 39)).Merge
Range(Cells(i, 40), Cells(i, 41)).Merge
Range(Cells(i, 42), Cells(i, 45)).Merge
Range(Cells(i, 46), Cells(i, 49)).Merge
Range(Cells(i, 50), Cells(i, 60)).Merge
If Worksheets(1).Cells(i, 2) <> "" And Worksheets(1).Cells(i, 8).Value = "" Then
Application.Goto Reference:=Worksheets(1).Cells(i, 8), Scroll:=False
End If
i = i + 1
Wend
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
ActiveSheet.Protect
End If
End Sub


試しにSheet2のB11~BH41に適当な数値を入れて
Sub test()
Range("B11:BH41").sort key1:=Range("B11"), order1:=xlAscending, Key2:=Range("L11"), Order2:=xlAscending
End Sub
として実行した場合はちゃんと並び替えが出来ました。

解決方法ご教示よろしくお願いいたします。

A 回答 (1件)

こんにちは



>sortしようとしたときに「オブジェクトが必要です」というエラーが出る
それって本当にSortメソッドで出ているエラーですか??

ざっと見たところ、
>x = Target.Column
で、エラーになりそうですけれど・・・?

単に、変数「Target」が未定義なためにエラーが起きているだけではないでしょうか?
それとも、グローバルな変数として定義されているのでしょうか?
もしそうであるなら、実行時のTargetの内容はどうなっていますか?
    • good
    • 0
この回答へのお礼

こんにちは、ご教示ありがとうございます。
以前、
Range("B11:BH41").sort key1:=Range("B11"), order1:=xlAscending, Key2:=Range("L11"), Order2:=xlAscending
だった部分は
Call Range("B11:BH41").Sort(key1:=Range("B11"), order1:=xlAscending)
でした。その時は「オブジェクトが必要です」と出ていなかったのでそこがおかしいのかと思っていたのですが、一行目の
Sub sort2keys()
の部分も
Private Sub Worksheet_Change(ByVal Target As Range)から変更していたのを忘れていました。

1行目の部分を
Private Sub Worksheet_Change(ByVal Target As Range)
に戻したら正常に動いたのでSortは関係ありませんでした。

すみませんでした。

お礼日時:2021/05/08 13:57

お探しのQ&Aが見つからない時は、教えて!gooで質問しましょう!