鉴于被调用的过程实际上设置了传递的Range对象ByRef,我期望对象引用在调用过程中可用。但它仍然没有。
修复是什么?
调用
Private Sub Specs_TryGetRangeFromDefinedName_CanFindGlobalName()
Dim Specs As New SpecSuite
Dim rngResult As Excel.range
Dim bResult As Boolean
bResult = TryGetRangeFromDefinedName(rngResult, "LongTermTaxRate", ThisWorkbook.Name)
With Specs.It("should return refersTo range when the name is global")
.Expect(bResult).ToEqual True
.Expect(rngResult.address).ToEqual "$B$2" ** FAIL (object is Nothing)2
End With
SpecRunner.RunSuite Specs
End Sub
称为
Public Function TryGetRangeFromDefinedName(ByRef aRange As Excel.range, _
ByRef aName As String, _
ByRef aWkbName As String, _
Optional ByRef aSheetName As String = vbNullString) As Boolean
Dim rngResult As Excel.range
If IsValued(aName) And IsValued(aWkbName) Then
On Error Resume Next
If IsValued(aSheetName) Then
' local name (presumably)
Set rngResult = Workbooks(aWkbName).Worksheets(aSheetName).range(aName)
Else
' global name (presumably)
Set rngResult = Workbooks(aWkbName).Names(aName).RefersToRange
End If
TryGetRangeFromDefinedName = (err.Number = 0)
On Error GoTo 0
End If
End Function
答案 0 :(得分:4)
从不使用参数aRange
,并且已分配rngResult
但从未引用过。摆脱rngResult
并改为分配aRange
。
此外,如果String
参数已通过ByVal
,则您的方法的意图会更清晰,因为它们未被分配。
这些观察结果都是Rubberduck代码检查结果(免责声明:我共同拥有这个项目)。