在单元格引用中删除和替换 sheet

Deleting and replacing sheet on opening breaks in cell reference

又是我。

我有一个代码可以在 wb_open 上导入引用 sheet。我正在尝试一些新的东西来让我的代码更快,但它产生了一个问题。

我的新代码删除(而不是复制粘贴)现有的内部参考 sheet 并由外部(刷新与否)替换。

问题是因为删除内部引用 sheet 删除了我对那个 sheet 的单元格引用,即使我将新复制的 sheet 命名为完全相同的名称.有办法绕过吗?

Sub Workbook_open()
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.DisplayAlerts = False
Dim Sheetname As String
Sheetname = "cédule détaillée 2 "

Worksheets(Sheetname).Visible = True

Dim externalwb As Workbook
Set externalwb = Workbooks.Open(fileName:="\Backup\Opérations\Coaticook\Planification\Cédule détaillées\Cédule détaillées des composantes.xlsx")

Dim curentSheetNumber As Long
currentSheetNumber = ThisWorkbook.Worksheets(Sheetname).Index
ThisWorkbook.Worksheets(Sheetname).Delete
externalwb.Worksheets(Sheetname).Copy After:=ThisWorkbook.Worksheets(currentSheetNumber - 1)
externalwb.Close False

Worksheets(Sheetname).Visible = False
Application.ScreenUpdating = True

       
Application.EnableEvents = True
Application.ScreenUpdating = True

End Sub

请尝试实施下一个公式复制方法:

Sub testCopyFormulas()
  Dim sh As Worksheet, rngForm As Range, shN As Worksheet
  Set sh = ActiveSheet
   Set rngForm = sh.UsedRange.SpecialCells(xlCellTypeFormulas)
   Set shN = Worksheets.Add

   shN.Range(rngForm.Address).Formula = rngForm.Formula
End Sub

特别是在您的代码中,尝试这种方法:

'...your code...
 Dim externalwb As Workbook, rngForm As Range
 Set externalwb = Workbooks.Open(fileName:="\Backup\Opérations\Coaticook\Planification\Cédule détaillées\Cédule détaillées des composantes.xlsx")

 Dim curentSheetNumber As Long
 Set rngForm = ThisWorkbook.Worksheets(Sheetname).SpecialCells(xlCellTypeFormulas)
 currentSheetNumber = ThisWorkbook.Worksheets(Sheetname).Index
 ThisWorkbook.Worksheets(Sheetname).Delete
 externalwb.Worksheets(Sheetname).Copy After:=ThisWorkbook.Worksheets(currentSheetNumber - 1)
 externalwb.Close False
 ThisWorkbook.Worksheets(Sheetname).Range(rngForm.Address).Formula = rngForm.Formula
 '...Your code...