我正在尝试提出一个VBA公式,它将获取一个单元格,并返回该单元格引用的范围。这就是我到目前为止所做的:
Function GetAddressCellPointsTo(ByRef src As Range) As Range
On Error GoTo InvalidSrc
referenceText = Replace(src.Formula, "=", "")
Set GetAddressCellPointsTo = Range(referenceText)
Exit Function
InvalidSrc:
err.Raise 1, "GetAddressCellPointsTo", "The formula of the source cell must be a single reference to another cell or range."
End Function
问题是我知道如果单元格不包含有效范围,或者引用在源单元格中没有完全限定(即=A1
vs {{1或者,如果单元格指向命名范围。
我想做的是将引用可靠地拉到范围,如果这是单元格所指向的范围,否则返回错误信息。
答案 0 :(得分:1)
以下是我认为符合您要求的略微修改:
Function GetAddressCellPointsTo(ByRef src As Range) As Range
referenceText = Replace(src.Formula, "=", "")
On Error Resume Next
'Return err.Number 1004 if referenceText not on current sheet
Set GetAddressCellPointsTo = src.Parent.Range(referenceText)
If Err.Number <> 0 Then
On Error GoTo InvalidSrc
Set GetAddressCellPointsTo = Range(referenceText)
End If
Exit Function
InvalidSrc:
Err.Raise 1, "GetAddressCellPointsTo", "The formula of the source cell must be a single reference to another cell or range."
End Function
这将首先在src所在的工作表上找到参考。如果失败,对于不在工作表上的任何参考,它会尝试而不指定工作表。