以编程方式更新在MS Word 2010中的Excel对象的链接命名范围

时间:2018-06-28 03:52:26

标签: vba excel-vba word-vba excel

我已经仔细阅读了您在以下链接中发布的上述答案。

Programmatically Update Linked Named Range of excel object in MS Word (2007)

使用上述相同步骤更新共享驱动器路径时遇到问题。我的excel文件位于共享驱动器文件夹中,我尝试手动放入OLE对象,成功了。使用类似的逻辑时:

ActiveDocument.Bookmarks("R1").Range.InlineShapes.AddOLEObject filename:=filename _
  & "!Range1", LinkToFile:=True"

它给了我以下错误:

  

Word无法创建指向您指定对象的链接。请   将对象直接插入文件中而不创建链接

我无法弄清楚为什么会出现此错误。在这方面的任何帮助将不胜感激。

注意:我正在更新一个新范围以及文件位置和文件名。我已经验证了excel文件中的范围是有效的。

谢谢

2 个答案:

答案 0 :(得分:2)

由于链接已经存在,因此您不应使用.AddOLEObject。相反,您应该编辑文件路径。例如:

Dim iShp As InlineShape
Const strPath As String = "New Path"
For Each iShp In ActiveDocument.InlineShapes
  With iShp
    If Not .LinkFormat Is Nothing Then
      With .LinkFormat
        .SourceFullName = Replace(.SourceFullName, .SourcePath, strPath)
      End With
      With .Field
        .Code.Text = Replace(.Code.Text, "5 - EW_RA!R2C17", "6 - EW_RA!R2C17")
        .Update
      End With
    End If
  End With
Next

答案 1 :(得分:0)

对于具有早期绑定的包装对象:

Dim wdApp As New Word.Application, wdDoc As Word.Document
Dim wdShp As Word.Shape, wdRng As Word.Range, i As Long, Fmt As Long, StrID As String, StrNm As String
Dim vRel As Long, vPos As Single, hRel As Long, hPos As Single, Hght As Single, Wdth As Single
Const strPath As String = "New Path"
With wdApp
  .Visible = True
  Set wdDoc = .Documents.Open(Filename:="C:\Users\" & Environ("Username") & "\Documents\Target Document.docx", _
    AddToRecentFiles:=False, Visible:=True)
  With wdDoc
    For i = .Shapes.Count To 1 Step -1
      With .Shapes(i)
        If Not .LinkFormat Is Nothing Then
          Set wdRng = .Anchor: StrID = .OLEFormat.progID: StrNm = "\" & .LinkFormat.SourceName
          Fmt = .WrapFormat.Type: Hght = .Height: Wdth = .Width
          vRel = .RelativeVerticalPosition:   vPos = .Top
          hRel = .RelativeHorizontalPosition: hPos = .Left
          .Delete
        With wdRng
          .Fields.Add Range:=.Duplicate, Type:=wdFieldEmpty, PreserveFormatting:=False, _
          Text:="LINK " & StrID & " " & Chr(34) & Replace(strPath & StrNm, "\", "\\") & Chr(34) & " " & _
            "6 - EW_RA!R2C17" & " \p"
          .End = .End + 1
          Set wdShp = .Fields(1).InlineShape.ConvertToShape
        End With
        With wdShp
          .WrapFormat.Type = Fmt: .Height = Hght: .Width = Wdth
          .RelativeVerticalPosition = vRel:   .Top = vPos
          .RelativeHorizontalPosition = hRel: .Left = hPos
          End With
        End If
      End With
    Next
    .Close True
  End With
  .Quit
End With