Excel VBA更新链接

时间:2018-12-23 18:13:20

标签: excel vba

我正在尝试设置VBA宏以更新excel中的链接路径。我在网上查找了一些代码,并试图将它们放在一起,但出现了错误。我想知道我是否可以在这里找到方向。请注意,我不是专业的程序员,只是试图减少一些手动更新工作。

干杯!

私人子CommandButton1_Click()

Dim FolderPath As String
Dim FSO As Object
Dim bookname As String
Dim wbook As Workbook
Dim oldname As String
Dim newname As String

oldname = "C:\Users\XX\Documents\[Broadstreet.xlsx]"

newname = "C:\Users\XX\Documents\[Broadstreet2.xlsx]"

FolderPath = "C:\Users\XX\Documents1"


With Application
    .ScreenUpdating = False
    .AskToUpdateLinks = False
End With


For Each Workbook In FSO.GetFolder(FolderPath).Files
    bookname = Workbook.Name

    MsgBox (bookname)

    Set wb = Workbooks.Open(FolderPath & "\" & bookname)

   ActiveWorkbook.ChangeLink oldname1, newname1, xlLinkTypeExcelLinks


   wb.Close SaveChanges:=True

Next

Application.ScreenUpdating = True

结束子

1 个答案:

答案 0 :(得分:0)

用于文件夹处理的工作簿

  
      
  • 浏览文件夹中的所有Excel文件(工作簿),打开每个文件,将链接从一个文档更改为另一个文档,保存更改并关闭工作簿。
  •   
  • xlLinkTypeExcelLinksType默认参数 ChangeLink方法的参数,因此可以省略。
  • .Close True可以按这种方式使用,因为SaveChangesClose方法的 first 自变量。

代码

Private Sub CommandButton1_Click()

  Const strOld As String = "C:\Users\XX\Documents\[Broadstreet.xlsx]"
  Const strNew As String = "C:\Users\XX\Documents\[Broadstreet2.xlsx]"
  Const strPath As String = "C:\Users\XX\Documents1"
  Const strExt As String = "*.xls*"

  Dim strName As String

  With Application
    .ScreenUpdating = False
    .AskToUpdateLinks = False
  End With

  On Error GoTo ProcedureExit

  strName = Dir(strPath & "\" & strExt)

  Do While strName <> ""
    With Workbooks.Open(strPath & "\" & strName)
      .ChangeLink strOld, strNew
      .Close True
    End With
    strName = Dir
  Loop

ProcedureExit:
  With Application
    .AskToUpdateLinks = True
    .ScreenUpdating = True
  End With

End Sub