下面提到的代码由@simoco编写。我需要一个小小的修正。该代码适用于两个范围。我希望代码只运行列A:E
。换句话说,目前如果我在A:E
以外的任何列中选择一个单元格,则在运行代码时,只选择两个单元格。我不希望这种情况发生。如果我在A:E
中选择任何单元格,我希望选择A:E
。如果我没有在列A:E
中选择单元格,则代码不应运行并且应显示消息框:
msgbox("Please select a cell in columns A:E").
请帮忙。
代码是:
Sub test1()
Dim rng As Range
Dim ar As Range
Dim rngAE As Range, cell As Range
With Selection
For Each ar In .Areas
If rng Is Nothing Then
Set rng = ar.Resize(1, 2)
Else
Set rng = Union(rng, ar.Resize(1, 2))
End If
Next ar
Set rngAE = Intersect(.Cells, Range("A:E"))
If Not rngAE Is Nothing Then
For Each cell In rngAE
Set rng = Union(rng, Range("A" & cell.Row & ":E" & cell.Row))
Next cell
End If
End With
rng.Select
End Sub
答案 0 :(得分:0)
尝试更改此内容:
Set rngAE = Intersect(.Cells, Range("A:E"))
If Not rngAE Is Nothing Then
For Each cell In rngAE
Set rng = Union(rng, Range("A" & cell.Row & ":E" & cell.Row))
Next cell
End If
到此:
Set rngAE = Intersect(.Cells, Range("A:E"))
If Not rngAE Is Nothing Then
For Each cell In rngAE
Set rng = Union(rng, Range("A" & cell.Row & ":E" & cell.Row))
Next cell
Else
msgbox "Please select a cell in columns A:E", vbCritical
Exit Sub
End If