转到引用单元格的VBA代码

时间:2017-02-07 14:53:42

标签: excel vba excel-vba

您好我正在尝试编写一个宏,该宏转到公式中引用的单元格。例如,如果我们有以下公式:

=IF(Sheet2!C3="","",Sheet2!C3)

我希望宏将我带到Sheet2 C3。 所以我发现这个代码感谢你们:

Dim rLast As Range, iLinkNum As Integer, iArrowNum As Integer
    Dim stMsg As String
    Dim bNewArrow As Boolean
    Application.ScreenUpdating = False
    ActiveCell.ShowPrecedents
    Set rLast = ActiveCell
    iArrowNum = 1
    iLinkNum = 1
    bNewArrow = True
    Do
        Do
            Application.Goto rLast
            On Error Resume Next
            ActiveCell.NavigateArrow TowardPrecedent:=True, ArrowNumber:=iArrowNum, LinkNumber:=iLinkNum
            If Err.Number > 0 Then Exit Do
            On Error GoTo 0
            If rLast.Address(external:=True) = ActiveCell.Address(external:=True) Then Exit Do
            bNewArrow = False
            If rLast.Worksheet.Parent.Name = ActiveCell.Worksheet.Parent.Name Then
                If rLast.Worksheet.Name = ActiveCell.Parent.Name Then
                     ' local
                    stMsg = stMsg & vbNewLine & Selection.Address
                Else
                    stMsg = stMsg & vbNewLine & "'" & Selection.Parent.Name & "'!" & Selection.Address
                End If
            Else
                 ' external
                stMsg = stMsg & vbNewLine & Selection.Address(external:=True)
            End If
            iLinkNum = iLinkNum + 1 ' try another  link
        Loop
        If bNewArrow Then Exit Do
        iLinkNum = 1
        bNewArrow = True
        iArrowNum = iArrowNum + 1 'try another arrow
    Loop
    rLast.Parent.ClearArrows
    Application.Goto rLast
    MsgBox "Precedents are" & stMsg

    Exit Sub

Range("stMsg").Select
Selection.Goto

变量包含单元格的名称。如何让宏去?名称格式为'Sheet2'!$ C $ 3

2 个答案:

答案 0 :(得分:0)

具体针对这种情况:

Dim rng As Range  
Dim tmp As String  

tmp = Right(Selection.Formula, Len(Selection.Formula) - InStrRev(Selection.Formula, ","))  
Set rng = Range(Left(tmp, Len(tmp) - 1))  

答案 1 :(得分:0)

这个怎么样:

With Range("'Sheet2'!$C$3")
    .Parent.Activate
    .Activate
End With

您可以将'Sheet2'!$C$3替换为您在宏中找到的地址。