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

お世話になります。
複数行にわたって選択しているときに実行するとエラーメッセージを出したいとします。現状では、
If Selection.Rows.Count <> 1 Then
subMsgBox "You are selecting two or more rows"
Exit Sub
End If
としていますが、これではドラッグで連続した行を選択している場合には正しくエラーになりますが、Ctrlクリックでポンポンと飛ばし飛ばしクリックしている場合はエラーになりません。
If Selection.Cells.Count <> 1 Then
だと同じ行の複数個所を選んだ場合もエラーになってしまいます。
If Selection.Cells.EntireRow.Count <> 1 Then
If Selection.Cells.EntireRow.Rows.Count <> 1 Then
でもCtrl+クリックの場合にダメです。
どうしたらいいでしょうか。
よろしくお願いします。

A 回答 (2件)

'MSDNライブラリのApplication.SelectionがObjectで


'つなげられるプロパティが書かれていないってのは問題があると思う。
'いくつかのサイトではAreasというプロパティがあると
'述べていたのでそれを使って自力で実装した

Option Explicit

Sub hoge()
Dim x As Collection
Dim i As Range
Dim j As Object 'Cell型がないようなので
Dim k As Integer
Dim flag As Boolean

Set x = New Collection
For Each i In Selection.Areas '1から始まるらしい
For Each j In i.Cells
If Not CollectionhasItem(x, j.Row) Then
x.Add (j.Row)
End If
Next j
Next

If x.Count > 1 Then
MsgBox ("You selected more than 2 rows")
End If

End Sub

Function CollectionhasItem(ByRef c As Collection, ByVal v As Integer)
Dim i As Integer
'For Each i In c ' For Each i in cってかけないらしい
'GenericsのあるVB.NETならともかく
For i = 1 To c.Count
If c(i) = v Then
CollectionhasItem = True
Exit Function
End If
Next
CollectionhasItem = False



End Function
    • good
    • 0

こんなんでどうすか



Sub test()
Dim TempRG As Range
Dim TempRow As Long

TempRow = Selection.Row

'選択しているセルのアドレスをRangeで包んでループ
For Each TempRG In Range(Selection.Address)
If TempRG.Row <> TempRow Then
MsgBox "You are selecting two or more rows"
Exit Sub
End If
Next

End Sub
    • good
    • 0
この回答へのお礼

みなさん、回答ありがとうございます。
マッチポンプですみません、過去の質問の回答を眺めていたらこれでいしのげそうな気がします。

If Intersect(Selection.Cells.EntireRow, 1).Count <> 1 Then
MsgBox "You are selecting two or more rows"
Exit Sub
End If

みなさんのコードも研究します。
ありがとうございます!

お礼日時:2009/04/16 15:45

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