从同一工作表vba中的另一个单元格访问超链接单元格

时间:2016-08-14 07:45:52

标签: excel vba excel-vba excel-formula

以下是我的工作表的设置:

enter image description here

单元格M7被超链接到大合并单元格E6。我的代码需要从M7(将是E6)访问目标单元的地址,并将该地址分配给名为“testing”的范围变量。

一旦我使用“testing”获得超链接目标单元格(E6)的地址,我就可以格式化“测试”的范围地址,但是我想要。

这是我到目前为止所尝试的内容

Dim lcell As Range
Dim testing As Range

        testing = lcell.Hyperlinks(1).Range
        testing.Value = "TEST"

这给了我以下错误:

  Run-time error: 91

  Object variable or With block variable not set

2 个答案:

答案 0 :(得分:2)

此函数将返回对超链接目标范围的引用,无论超链接是由HYPERLINK WorkSheetFunction还是在单元格的超链接集合中设置的。

Sub Example()

    Dim lcell As Range
    Dim TestRange As Range

    Set lcell = Range("A1")

    Set TestRange = getHyperLinkTarget(lcell)

    If Not TestRange Is Nothing Then

        TestRange.Value = "TEST"

    End If

End Sub
Function getHyperLinkTarget(HSource As Range) As Range
    Dim address As String, formula As String
    formula = HSource.formula
    If HSource.Hyperlinks.Count > 0 Then
        address = HSource.Hyperlinks(1).SubAddress
    ElseIf InStr(formula, "=HYPERLINK(") Then
        address = Mid(formula, InStr(formula, "(") + 1, InStr(formula, ",") - InStr(formula, "(") - 1)
    End If

    On Error Resume Next
    If Len(address) Then Set getHyperLinkTarget = Range(address)
    On Error GoTo 0
End Function

感谢ThunderFrame指出了HYPERLINK工作表功能。

答案 1 :(得分:2)

这应该做你以后做的事情。您需要解析M7公式的内容,因此我的代码假定M7公式包含超链接公式,如:

=HYPERLINK(E6,"RSDS")

VBA看起来像:

Sub foo()

  Const hyperlinkSignature = "=HYPERLINK("

  Dim rng As Range
  Set rng = Range("M7")

  Dim hyperlinkFormula As String
  hyperlinkFormula = Range("M7").formula

  Dim testing As Range

  'Check the cell contains a hyperlink formula
  If StrComp(hyperlinkSignature, Left(hyperlinkFormula, Len(hyperlinkSignature)), vbTextCompare) = 0 Then
    Dim hyperlinkTarget As String
    hyperlinkTarget = Mid(Split(hyperlinkFormula, ",")(0), Len(hyperlinkSignature) + 1)

    Set testing = Range(hyperlinkTarget)

    testing.Value = "TEST"

  Else
    'Check if the cell is a hyperlinked cell
    If Range("M7").Hyperlinks.Count = 1 Then
      'Credit to Thomas for this line
      Set testing = Range(Range("M7").Hyperlinks(1).SubAddress)
      testing.Value = "TEST"
    End If

  End If

End Sub

或者,如果你想要一个不需要检查M7公式包含超链接的简短方法,你可以使用:

Dim target As Range
Set target = Range(Range("M7").DirectPrecedents.Address)
target.Value = "Test"