使用VBA删除公式中对文件名的引用

我试图从Excel工作簿中复制一系列工作表,并将其粘贴到新的工作簿中。 我遇到的问题是,当我将工作表复制到新的工作簿中时,公式仍旧是对公式中旧工作簿的引用。 我试图获取工作簿的名称,并用空字符replace,但我相信我的代码是引用新的工作簿,而不是旧的。 我尝试了一个函数,以及“ThisWorkbook”以及“ActiveWorkbook”,但似乎没有任何工作。

这是function….

Function MyName() As String MyName = ThisWorkbook.Name End Function 

这里是完整的代码….

 Sub CopyToNewWorkbook() Dim ws As Worksheet Dim i As Integer Dim wbCurrent As Workbook Dim wbName As Variant Dim wbNew As Workbook 'wbName = ActiveWorkbook.Name 'wbName = ThisWorkbook.Name Set wbCurrent = ActiveWorkbook Set wbNew = Workbooks.Add For Each ws In wbCurrent.Sheets Do While wbNew.Sheets.Count <= (wbCurrent.Sheets.Count - 3) For i = 3 To wbCurrent.Sheets.Count wbCurrent.Sheets(i).Copy after:=wbNew.Sheets(wbNew.Sheets.Count) Next i Loop Next ws wbNew.Activate Sheets("Sheet1").Select ActiveWindow.SelectedSheets.Delete Cells.Replace What:=MyName, Replacement:="", LookAt:=xlPart, SearchOrder:=xlByRows, _ MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False End Sub 

你不能只使用BreakLinks方法吗?

 'Get all links ExternalLinks = wbNew.LinkSources(Type:=xlLinkTypeExcelLinks) 'Break each link For x = 1 To UBound(ExternalLinks) wbNew.BreakLink Name:=ExternalLinks(x), Type:=xlLinkTypeExcelLinks Next x 

我能用下面的代码得到预期的结果。

  Sub CopyToNewWorkbook() Dim ws As Worksheet Dim i As Integer Dim wbCurrent As Workbook Dim wbName As Variant Dim wbNew As Workbook Call MyName wbName = MyName Set wbCurrent = ActiveWorkbook Set wbNew = Workbooks.Add For Each ws In wbCurrent.Sheets ws.Visible = xlSheetVisible Do While wbNew.Sheets.Count <= (wbCurrent.Sheets.Count - 3) For i = 3 To wbCurrent.Sheets.Count wbCurrent.Sheets(i).Copy after:=wbNew.Sheets(wbNew.Sheets.Count) Next i Loop Next ws wbNew.Activate Sheets("Sheet1").Select ActiveWindow.SelectedSheets.Delete Cells.Replace What:=MyName, Replacement:="", LookAt:=xlPart, SearchOrder:=xlByRows, _ MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False Cells.Replace What:="'[" & wbName & "]", Replacement:="'", LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:= _ False, SearchFormat:=False, ReplaceFormat:=False End Sub