逻辑是找到第一行,第一列,总行数,总列数,然后推断出你想要的范围。让我用一个例子来解释它。我已经对代码进行了注释,以便您理解它不会有任何问题。
Sub Sample()
Dim TestRange As Range
Dim rng1 As Range, rng2 As Range, rng3 As Range, FinalRange As Range
Dim ws As Worksheet
Dim r As Long, c As Long
Set ws = ThisWorkbook.Sheets("Sheet1")
With ws
Set TestRange = .Range("A3:B10")
Debug.Print "Our Sample Range is " & TestRange.Address
'~~> This will give you 8
Debug.Print "Total Rows in the range is " & TestRange.Rows.Count
'~~> This will give you 3 From A3
Debug.Print "The First Row in the range is " & TestRange.Row
'~~> This will give you 1 From A3
Debug.Print "The First Column in the range is " & TestRange.Column
r = TestRange.Row
c = TestRange.Column
'~~> This will give you 2
Debug.Print "Total Columns in the range is " & TestRange.Columns.Count
ColCount = TestRange.Columns.Count
'~~> This is give you the 1st row in that range $A$3:$B$3
Debug.Print "The First Row address is " & Range(.Cells(r, c), _
.Cells(r, c + ColCount - 1)).Address
Set rng1 = Range(.Cells(r, c), .Cells(r, c + ColCount - 1))
'~~> This will give you the last row
Debug.Print "The Last Row address is " & _
Range(.Cells(r + TestRange.Rows.Count - 1, c), _
.Cells(r + TestRange.Rows.Count - 1, c + ColCount - 1)).Address
Set rng2 = Range(.Cells(r + TestRange.Rows.Count - 1, c), _
.Cells(r + TestRange.Rows.Count - 1, c + ColCount - 1))
'~~> This will give you the Second last row
Debug.Print "The Second Last Row address is " & _
Range(.Cells(r + TestRange.Rows.Count - 2, c), _
.Cells(r + TestRange.Rows.Count - 2, c + ColCount - 1)).Address
Set rng3 = Range(.Cells(r + TestRange.Rows.Count - 2, c), _
.Cells(r + TestRange.Rows.Count - 2, c + ColCount - 1))
'~~> This will give you the final range i.e $A$3:$B$3,$A$9:$B$10
Set FinalRange = Union(rng1, rng2, rng3)
Debug.Print "The Final Range address is " & FinalRange.Address
End With
End Sub
当您运行上述代码时,您会在即时窗口中获得此输出
Our Sample Range is $A$3:$B$10
Total Rows in the range is 8
The First Row in the range is 3
The First Column in the range is 1
Total Columns in the range is 2
The First Row address is $A$3:$B$3
The Last Row address is $A$10:$B$10
The Second Last Row address is $A$9:$B$9
The Final Range address is $A$3:$B$3,$A$9:$B$10
编辑
所以上面的代码减去调试语句和正确的变量声明可以写成
Sub Sample()
Dim TestRange As Range
Dim rng1 As Range, rng2 As Range, rng3 As Range, FinalRange As Range
Dim ws As Worksheet
Dim r1 As Long, c1 As Long, rCount As Long, cCount As Long
Set ws = ThisWorkbook.Sheets("Sheet1")
With ws
Set TestRange = .Range("A3:B10")
rCount = TestRange.Rows.Count
r1 = TestRange.Row
cCount = TestRange.Columns.Count
c1 = TestRange.Column
Set rng1 = Range(.Cells(r1, c1), .Cells(r1, c1 + cCount - 1))
Set rng2 = Range(.Cells(r1 + rCount - 1, c1), _
.Cells(r1 + rCount - 1, c1 + cCount - 1))
Set rng3 = Range(.Cells(r1 + rCount - 2, c1), _
.Cells(r1 + rCount - 2, c1 + cCount - 1))
Set FinalRange = Union(rng1, rng2, rng3)
Debug.Print "The Final Range address is " & FinalRange.Address
End With
End Sub