excel 将每个工作表中的超链接添加回TOC工作表[重复]

xyhw6mcr  于 2023-05-01  发布在  其他
关注(0)|答案(2)|浏览(188)

此问题已在此处有答案

How to add text to display for a Hyperlink in Excel Spreadsheet Using VBScript(1个答案)
2天前关闭。
我有一个Excel工作簿,其中第一个工作表作为TOC工作表,其他许多工作表作为内容。我想使用VBScript添加超链接到每个表,可以链接回TOC表。有熟悉VBScript的人可以帮我吗?
下面是我创建的VBScript代码,但是我在第11行得到了一个错误消息“未知的运行时错误”。

Dim objExcel
   Set objExcel = CreateObject("Excel.Application") 
   Wscript.Sleep 30
   objExcel.Application.Visible = False
   Set objWorkbook = objExcel.Workbooks.Open("path\test.xlsx",,False)
   objExcel.Application.DisplayAlerts = False
   objExcel.Workbooks(1).Activate
   Dim ShCount, sHyperlink, sDest
   ShCount = objExcel.Workbooks(1).Worksheets.Count
   For I = 2 To ShCount
Set sHyperlink=objExcel.Workbooks(1).Worksheets(I).Cells("A1")
Set sDest=objExcel.Workbooks(1).Worksheets(1).Cells("A1")
Call sHyperlink.Parent.Hyperlinks.Add(sHyperlink, vbNullString, "'" & sDest.Parent.Name & "'!" & sDest.Address, vbNullString, sHyperlink.Value)
   Next
objExcel.Workbooks(1).SaveAs "path\test.xlsx", 51 
objExcel.Quit
set objExcel = nothing
v6ylcynt

v6ylcynt1#

您可以通过在单元格中添加=HYPERLINK()公式来实现:
就像

objExcel.Workbooks(1).Worksheets(I).Cells("A1").Formula="HYPERLINK(""#'IndexSheetName'!A2"",""UserFriendlyName"")"
b5lpy0ml

b5lpy0ml2#

添加指向TOC工作表的超链接

Option Explicit

' Create and reference a new instance of Excel ('xlApp'). 
Dim xlApp: Set xlApp = CreateObject("Excel.Application") 
'xlApp.Visible = True ' use this while developing; it's 'False' by default

'Wscript.Sleep 30 ' ???

' Open and reference the workbook ('wb').
Dim wb: Set wb = xlApp.Workbooks.Open("path\Test.xlsx")

'xlApp.DisplayAlerts = False ' ???

' Store the number of worksheets in a variable ('wsCount').
Dim wsCount: wsCount = wb.Worksheets.Count
' Store the destination address, the parameter for the 3rd argument
' of 'Hyperlinks.Add', 'SubAddress', in a variable ('dAddress').
Dim dAddress: dAddress = "'" & wb.Worksheets(1).Name & "'!A1"

Dim sCell, sValue, i

For i = 2 To wsCount
    Set sCell = wb.Worksheets(i).Range("A1")
    sValue = vbNullString
    On Error Resume Next ' prevent Type mismatch error if error value
        sValue = CStr(sCell.Value)
    On Error Goto 0    
    ' The parameter of the 2nd argument, 'Address',  must be an empty string.
    ' The parameter of the 5th argument, 'TextToDisplay', cannot be
    ' an empty string, but it can be omitted when its parameter will default
    ' to the destination address (e.g. 'Sheet1!A1') 
    ' or to whatever is in the cell.
    If Len(sValue) > 0 Then
        sCell.Worksheet.Hyperlinks.Add _
            sCell, vbNullString, dAddress, , sCell.Value
    Else
        sCell.Worksheet.Hyperlinks.Add sCell, vbNullString, dAddress
    End If
Next

wb.Close True 
xlApp.Quit

'Set xlApp = Nothing ' ???

相关问题