VBA Excel - 使用= HYPERLINK的应用程序或面向对象的错误

时间:2017-02-23 09:35:47

标签: excel-vba hyperlink vba excel

我在Excel 2016中遇到基于VBA的超链接的问题。我想添加一个"导航"在所有其他工作表之前的工作表,但我有" = HYPERLINK"的问题。我的代码如下:

Dim wbBook As workbook

Dim wsActive As Worksheet
Dim wsSheet As Worksheet

Dim lnRow As Long
Dim lnPages As Long
Dim lnCount As Long

Dim temp As Variant

Set wbBook = ActiveWorkbook

wbBook.Sheets.Add(Before:=Worksheets(1)).Name = "Navigation"

Set wsActive = wbBook.ActiveSheet

With wsActive
    .Name = "Navigation"
    With .Range("A1:A1")
        .Value = VBA.Array("Mitarbeiter")
        .Font.Bold = True
    End With
End With

lnRow = 2
lnCount = 1

For Each wsSheet In wbBook.Worksheets
    If wsSheet.Name <> wsActive.Name Then
        wsSheet.Activate
        With wsActive
            Worksheets("Navigation").Cells(lnRow, 1).Formula = _
            "=HYPERLINK(" & Chr(34) & "#" & "'" & wsSheet.Name & "'" & "!A" & lnRow & Chr(34) & ";" & Chr(34) & wsSheet.Name & Chr(34) & ")"      
        End With
        lnRow = lnRow + 1
        lnCount = lnCount + 1
    End If
Next wsSheet

我遇到的问题是当我添加&#34; =&#34;在HYPERLINK面前,错误&#34; Anwendungsder objektorientierter Fehler&#34; (弹出应用程序或面向对象的错误)。如果我在没有&#34; =&#34;的情况下运行宏,程序可以运行,但我手动必须在导航表中添加方程式符号。

提前干杯!

2 个答案:

答案 0 :(得分:0)

由于您已经在使用VBA,为什么不添加超链接的VBA功能(.Hyperlinks.Add)。

您可以在MSDN

上详细了解详情

我减少了ActiveSheetActivate的使用。

<强>代码

Option Explicit

Sub TestHyperlink()

Dim wbBook As Workbook
Dim wsActive As Worksheet
Dim wsSheet As Worksheet

Dim lnRow As Long
Dim lnPages As Long
Dim lnCount As Long
Dim temp As Variant

Set wbBook = ActiveWorkbook
Set wsActive = wbBook.Sheets.Add(Before:=Worksheets(1))
With wsActive
    .Name = "Navigation"
    With .Range("A1:A1")
        .Value = VBA.Array("Mitarbeiter")
        .Font.Bold = True
    End With
End With

lnRow = 2
lnCount = 1

For Each wsSheet In wbBook.Worksheets
    If wsSheet.Name <> wsActive.Name Then
        With wsSheet
            .Hyperlinks.Add Anchor:=Worksheets("Navigation").Range("A" & lnRow), _
                Address:="", SubAddress:="'" & .Name & "'!" & .Range("A" & lnRow).Address, _
                TextToDisplay:="#" & .Name
        End With
        lnRow = lnRow + 1
        lnCount = lnCount + 1
    End If
Next wsSheet

End Sub

答案 1 :(得分:0)

尝试使用逗号分隔公式的参数而不是分号。我认为强迫公式进入这样的细胞会忽略本地化。

    With wsActive
        Worksheets("Navigation").Cells(lnRow, 1).Formula = _
        "=HYPERLINK(" & Chr(34) & "#" & "'" & wsSheet.Name & "'" & "!A" & lnRow & Chr(34) & "," & Chr(34) & wsSheet.Name & Chr(34) & ")"      
    End With