如何在输入框中禁用多 row/column 选择?

How to disable multi row/column selection in inputbox?

如果用户同时 select 多行多列,我正在寻找一种方法来禁用我的输入框中的 multi selection。我试过这段代码:

Dim rng As Range
Set rng = Application.InputBox("dasdasd", "asdas", "", Type:=8)

If rng.Columns.Count > 1 And rng.Rows.Count > 1 Then
    MsgBox "Multiple selection allowed only within the same row or column"
    Exit Sub
Else
    'carry on
End If

我想做的是同时禁用多列和多行selection。 例如 - 如果我 select(使用 ctrl 键)范围 "D1:D5","D8:D10" 那么它是正确的,因为这是一列中的多行 selection BUT。如果我 select "D1:D5","E8:E10" 那么它应该弹出错误,msgbox,等等。如果只有一行或一列被 selected 那么它应该继续进行。如果已经 select 编辑了多行和多列,那么它应该退出 sub.

上面的代码总是 returns 一行或一列,无论我 select 跨越多少个范围 rows/columns。我已经尝试过当前区域方法,但这 select 整个区域,甚至我还没有 selected...

我将不胜感激。

您可以遍历这些区域并记录所选内容所覆盖的行和列。使用两个词典似乎有些过分,但似乎可以完成工作。

如果您的范围由几个不连续的区域组成,您的代码将只考虑第一个块,例如D1:D5

Sub x()

Dim oDicR As Object, oDicC As Object, rArea As Range, rCell As Range, rng As Range

Set oDicR = CreateObject("Scripting.Dictionary")
Set oDicC = CreateObject("Scripting.Dictionary")
Set rng = Application.InputBox("dasdasd", "asdas", "", Type:=8)

For Each rArea In rng.Areas
    For Each rCell In rArea
        oDicR(rCell.Row) = 1
        oDicC(rCell.Column) = 1
    Next rCell
    If oDicR.Count > 1 And oDicC.Count > 1 Then
        MsgBox "Multiple selection allowed only within the same row or column"
        Exit Sub
    End If
Next rArea

'do whatever

End Sub
Sub test()

Dim rng As Range, cl As Range, allRng As Range
Dim minRw As Long, minCl As Long, maxRw As Long, maxCl As Long

On Error Resume Next
Set rng = Application.InputBox("dasdasd", "asdas", "", Type:=8)
If rng Is Nothing Then
    MsgBox "You have not selected any range"
    Exit Sub
End If    
Err.Clear
On Error GoTo 0

minRw = rng.Cells(1, 1).Row
minCl = rng.Cells(1, 1).Column

For Each cl In rng
    If cl.Row < minRw Then minRw = cl.Row Else: If cl.Row > maxRw Then maxRw = cl.Row
    If cl.Column < minCl Then minCl = cl.Column Else: If cl.Column > maxCl Then maxCl = cl.Column
Next
Set allRng = Range(Cells(minRw, minCl), Cells(maxRw, maxCl))

If allRng.Rows.Count > 1 And allRng.Columns.Count > 1 Then
    MsgBox "Multiple selection allowed only within the same row or column"
    Exit Sub
End If

End Sub