首页 > 解决方案 > 更新工作簿链接源

问题描述

我正在使用 Java 代码 + Apache POI 库生成 Excel 表。在某些单元格中,我插入了对另一个工作表的引用,该工作表将不起作用并显示“#REF”——这很好。此处的目的是,一旦将生成的工作表移动到打算在其中使用的实际工作簿,这些单元格将正确更新和显示。

移动工作表时,单元格不会更新。我发现我必须更新链接源。

我已经整理了一些代码,这些代码将获取所有链接、迭代它们并将它们的源更新为当前打开的工作簿。

    Dim wbName As String
    Dim wbDir As String
    Dim i As Integer
    Dim wbLinks As Variant
    
    wbLinks = ActiveWorkbook.LinkSources(xlExcelLinks)
    
    If (UBound(wbLinks) > 0) Then
        wbName = Application.ActiveWorkbook.FullName
        wbDir = Left(wbName, InStrRev(wbName, "\"))
        wbDir = Left(wbDir, Len(wbDir) - 1)
        wbName = Mid(wbName, InStrRev(wbName, "\") + 1)

        ChDir wbDir
        For i = 1 To UBound(wbLinks)
            ActiveWorkbook.ChangeLink Name:=wbLinks(i), NewName:=wbName, Type:=xlExcelLinks
        Next i
    Else
        MsgBox ("No links found to update.")
    End If

所以这就是我尝试过的。我录制了自己手动执行此操作的宏(手动更新源代码有效),但即使在 VBA 中复制代码后,它也不起作用。


笔记:

单击单元格->单击公式框->按Enter = WORKS,完全没有错误。

按 CTRL + ALT + F9(和 SHIFT)不会更新单元格。

使用的两个公式:

=大师!B8

=管理!N10

标签: excelvba

解决方案


您可以尝试使用 VBA 重写公式。使用Range.SpecialCells 方法在工作表中查找所有有错误的公式:Set ErrFormulas = ThisWorkbook.Worksheets("Sheet1").Cells.SpecialCells(xlFormulas, xlErrors)

然后遍历这些以更新它们:

Option Explicit

Public Sub UpdateErrorFormulas()
    Dim ErrorOccured As Boolean
    ErrorOccured = False

    Dim ErrFormulas As Range
    Set ErrFormulas = ThisWorkbook.Worksheets("Sheet1").Cells.SpecialCells(xlFormulas, xlErrors)

    If ErrFormulas Is Nothing Then Exit Sub

    Dim Cell As Range
    For Each Cell In ErrFormulas
        Cell.Formula = Cell.Formula
    Next Cell
End Sub

推荐阅读