找到包含其他范围的最短矩形范围

时间:2015-04-07 20:03:42

标签: vb.net excel range add-in

假设我有以下范围:

$A$2:$C$3,$D$4:$E$5,$G$7

有一些方法组合可以给出包含这个方法的最短矩形范围吗?在我的例子中,答案应该是:

$A$2:$G$7

OBS:我使用VSTO 2013和VB.NET构建Excel 2013的加载项

谢谢!

1 个答案:

答案 0 :(得分:1)

您可以使用非连续范围的.Areas

Dim a, r1 As Long, c1 As Long, r2 As Long, c2 As Long, rng As Range
Range("$A$2:$C$3,$D$4:$E$5,$G$7").Select
Range("$A$2:$G$7").Select
r1 = Rows.Count: r2 = 1
c1 = Columns.Count: c2 = 1
With Range("$A$2:$C$3,$D$4:$E$5,$G$7")
    For Each rng In .Areas
        With rng
            If .Cells(1, 1).Row < r1 Then r1 = .Cells(1, 1).Row
            If .Cells(1, 1).Column < c1 Then c1 = .Cells(1, 1).Column
            If .Cells(.Rows.Count, 1).Row > r2 Then r2 = .Cells(.Rows.Count, 1).Row
            If .Cells(1, .Columns.Count).Column > c2 Then c2 = .Cells(1, .Columns.Count).Column
        End With
    Next rng
End With
Debug.Print Range(Cells(r1, c1), Cells(r2, c2)).Address(0, 0)

我不完全确定这将如何适应VB.Net/VSTO项目,但这就是如何在VBA中解决问题。这些方法应该可以很容易地转移到VB.Net中的Excel对象。