如何获取单元格公式引用的工作表

时间:2013-12-19 21:14:18

标签: excel vba

Function LinkedSheet(rgCell As Range) As Worksheet
'Returns the worksheet that the cell formula references
'Returns nothing if there's no formula
    Dim strFormula As String

    strFormula = rgCell.Cells(1, 1).Formula

    If (strFormula <> "") Then
        'Return the sheet that this range is linked to
    End If
End Function

有人可以帮我完成此功能吗?请记住,这应该适用于内部链接,外部链接以及带有名称空间的工作表链接,如“工作表1”

编辑: 为了回应Siddharth Rout,我之前曾尝试过

Function LinkedSheet(rgCell As Range) As Worksheet
'Returns the worksheet that the cell formula references
'Returns nothing if there's no formula
    Dim strFormula As String, sheetName As String

    strFormula = rgCell.Cells(1, 1).Formula

    If (strFormula <> "") Then
        'Return the sheet that this range is linked to
        sheetName = Mid(strFormula, 2, InStr(1, strFormula, "!") - 2)
        Set LinkedSheet = ThisWorkbook.Worksheets(sheetName)
    End If
End Function

对于名称中有空格的工作表失败。但是,我不愿意发布这个,因为我觉得必须有一个更好,更有效的方法来解决这个问题,我不想让人们的想法与我去的方向相同。

1 个答案:

答案 0 :(得分:1)

这是我的解决方案

Function LinkedSheet(rgCell As Range) As Worksheet
'Returns the worksheet that the cell formula references
'Returns nothing if there's no formula
    Dim strFormula As String, sheetName As String

    strFormula = rgCell.Cells(1, 1).Formula

    If (strFormula <> "") Then
        'Return the sheet that this range is linked to
        If (InStr(1, strFormula, "='") = 0) Then
            sheetName = Mid(strFormula, 2, InStr(1, strFormula, "!") - 2)
        Else
            sheetName = Mid(strFormula, 3, InStr(1, strFormula, "!") - 4)
        End If
        Set LinkedSheet = ThisWorkbook.Worksheets(sheetName)
    End If
End Function

我对它并不十分满意。我仍然认为可能有更好的方法,但这有效。