需要对较大范围的子范围的引用并不少见(至少对我而言)。 Range 构造函数(属性?在这种情况下对我来说似乎是一个构造函数)似乎只接受“A4:G7”类型的字符串参数——甚至不接受“R4C1:R7C7”风格,这更容易从行和列索引。
我认为 VBA 不允许重载,但令人恼火的是,MS 认为不适合为这类事情提供有用的功能。 AFAIK(在 VBA 中对我来说不是那么远)没有类似范围的构造函数接受行和列索引或单元格对。 .Rows 和 .Columns 属性也不符合我的预期。除了 .Rows.Count 和 .Columns.Count 之外,我不确定它们有什么用处(是我缺乏经验吗?没关系——帮帮我。)
我厌倦了编写简单但乏味的代码来将行和列索引内联转换为“A4:G7”样式的字符串,所以我编写了一个简单的函数来处理它。
在调用函数中:
dim row1 as long, col1 as long, row2 as long, col2 as long
dim subRng as Range
...
[Insert absolutely brilliant code here to compute row1, etc.,
or in my case, hack away until it works]
set subRng = getSubRange(row1, col1, row2, col2, bigRange)
...
[do great things with subRng]
这里是 getSubRange 实用函数:
Function getSubRange(iRow1 As Long, iCol1 As Long, _
iRow2 As Long, iCol2 As Long, _
sourceRange As Range) As Range
' Returns a sub-range of the source range (non-boolean version of makeSubRange().
' Inputs:
' iRow1 - Row and colunn indices in the sourceRange of
' iCol1 the upper left and lower right corners of
' iRow2 the requested subrange.
' iCol2
' sourceRange - The range from which a sub-range is requested.
'
' Return: Reference to a sub-range of sourceRange bounded by the input row and
' and column indices.
' Notes: A null range will be returned if the following is not true.
' 1 <= iRow1 <= SourceRange.Rows.count
' 1 <= iRow2 <= SourceRange.Rows.count
' 1 <= iCol1 <= SourceRange.Columns.count
' 1 <= iCol2 <= SourceRange.Columns.count
Const AM1 = 64 'Ascii value of 'A' = 65; Asc('A') - 1 = 64
Dim rangeStr As String
If (1 <= iRow1) And (iRow1 <= sourceRange.Rows.Count) And _
(1 <= iRow2) And (iRow2 <= sourceRange.Rows.Count) And _
(1 <= iCol1) And (iCol1 <= sourceRange.Columns.Count) And _
(1 <= iCol2) And (iCol2 <= sourceRange.Columns.Count) Then
rangeStr = Chr(AM1 + iCol1) & CStr(iRow1) & ":" _
& Chr(AM1 + iCol2) & CStr(iRow2)
Set getSubRange = sourceRange.Range(rangeStr)
Else
Set getSubRange = Nothing
End If
End Function 'getSubRange()
不要忘记子范围是对源范围的一部分的引用,而不是其中一部分的副本:您对子范围所做的任何更改都是对源范围的更改。但我想这已经足够明显了。