VBA 在另一个单元格中打开基于特定文本的超链接

问题描述

我正在尝试创建一个 VBA 来查看星期一的单元格 E,然后打开 D 中它旁边单元格中的超链接

我已经尝试了以下但它不起作用。当我运行它时什么也没有发生。超链接所附的文件位于我的网络上。

enter image description here

Sub OpenFile()
         Dim oH As Hyperlink
    For Each oH In Hyperlinks
          If oH.Range.Cells(1,2).Text = "Monday" Then If Dir(oH.Address) > "" Then Workbooks.Open oH.Address
    Next
End Sub 

解决方法

Sub OpenFile()
    Dim i As Long
    Dim rowLast As Long
    Dim filePath As String
    'Dim loopLink As Hyperlink 'Uncomment if there can be multiple links in column D cells
    
    With Sheet1 'Change the worksheet name to the correct one
        rowLast = .Range("E" & .Rows.Count).End(xlUp).Row
    
        For i = 2 To rowLast 'Loop from 2nd row to the last row
            If .Cells(i,5).Value = "Monday" Then 'Validation if cell in Column E is "Monday"
                With .Cells(i,4)
                    'Single link version,change to below version for multiple links
                    If .Hyperlinks.Count = 1 Then
                        filePath = .Hyperlinks(1).Address
                        If Dir(filePath) <> vbNullString Then Application.Workbooks.Open filePath
                    End If
                    
                    'Multiple links version
                    'For Each loopLink In .Hyperlinks
                    '   filePath = loopLink.Address
                    '   If Dir(filePath) <> vbNullString Then Application.Workbooks.Open filePath
                    'Next loopLink
                End With
            End If
        Next i
    End With
End Sub