如何获取单元格中超链接的工作簿的工作表中的单元格?

问题描述 投票:0回答:2

我有一个单元格区域,其中可以包含指向其他 Excel 数据的超链接。
Hyperlink in a cell]

我需要获取该超链接的特定工作表中的特定单元格。

我一开始尝试像这样拉工作表:

AktiveWorkbook.Sheets.Add Before:=c.Hyperlinks.Application.Worksheets(1)

最好的选择是我不必拉动工作表。

我在一个工作簿中,您可以在单元格 A1 中找到值“C:\Users\z0\Downloads\GG.xlsm”,这是关闭的工作簿的路径。

例如,我试图获取已关闭工作簿的 Sheet1 的 A1 单元格,并将值粘贴到工作簿中的 B1,您还可以在其中找到路径。

我尝试过:

Dim wb As Workbook: Set wb = ThisWorkbook
Dim sh As Worksheet: Set sh = wb.Worksheets(1)
Dim cell As Range: Set cell = sh.Range("A1:A1000")
Dim pth As String
Dim qafWb As Workbook

pth = Replace(Range("A1").Value, "\", "/")
qafWb = Workbooks(pth)
sh.Range("B2") = qafWb.Worksheets(1).Range("G13")

编译器说变量

qafWb
确实包含“Nothing”。

excel vba hyperlink cell worksheet
2个回答
0
投票

使用“超级”单元格 (VBA) 编写公式

  • 假设“超级”单元格中的公式类似于

    =HYPERLINK("C:\Users\z0\Downloads\GG.xlsm","Whatever")
    
Sub WriteFormulaUsingHyperCell()
   
    Const SRC_SHEET_NAME As String = "Sheet1"
    Const SRC_CELL As String = "A1"
    
    Const DST_SHEET_NAME As String = "Sheet1"
    Const DST_HYPER_CELL As String = "A1"
    Const DST_FORMULA_CELL As String = "B1"
    Const NOT_FOUND_STRING As String = "Not found"
    
    Dim IsSuccess As Boolean
    
    Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
    Dim dws As Worksheet: Set dws = wb.Sheets(DST_SHEET_NAME)
    
    Dim hStr As String: hStr = dws.Range(DST_HYPER_CELL).Formula
    Dim hParts() As String: hParts = Split(hStr, """")
    If UBound(hParts) < 1 Then GoTo WriteResult ' no double quotes
    
    Dim sFilePath As String: sFilePath = hParts(1)
    Dim Position As Long: Position = InStrRev(sFilePath, "\")
    If Position = 0 Then GoTo WriteResult ' no backslashes
                
    Dim sFolderPath As String: sFolderPath = Left(sFilePath, Position)
    Dim sFileName As String:
    sFileName = Right(sFilePath, Len(sFilePath) - Position)
    
    Dim dFormula As String: dFormula = "='" & sFolderPath & "[" & sFileName _
        & "]" & SRC_SHEET_NAME & "'!" & SRC_CELL
    
    IsSuccess = True
    
    'Debug.Print sFilePath
    'Debug.Print sFileName
    'Debug.Print dFormula
    
WriteResult:
    
    With dws.Range(DST_FORMULA_CELL)
        If IsSuccess Then
            .Formula = dFormula
        Else
            .Value = NOT_FOUND_STRING
        End If
    End With
    
End Sub

0
投票

假设您的工作表中的单元格

A1
中有一个文件名,其路径例如
C:\Users\z0\Downloads\GG.xlsm

E1
中填写工作表的名称,例如
Sheet1
,在
F1
中单元格的地址,例如
A1

A4
中您要读取该值。 您可以使用这样的宏:

Sub ReadFromFile()
    Dim adr As String, path As String, filename As String
    Dim shname As String, celladr As String
    adr = Range("A1").Value
    path = Left(adr, InStrRev(adr, "\"))
    filename = Mid(adr, InStrRev(adr, "\") + 1)
    shname = Range("E1").Value
    celladr = Range("F1").Value
    On Error Resume Next
    Range("A4").Formula = "='" & path & "[" & filename & "]" & shname & "'!" & celladr
    On Error GoTo 0
End Sub
© www.soinside.com 2019 - 2024. All rights reserved.