如何在不更改引用的情况下将Excel工作表复制并粘贴到新书中?

时间:2018-06-05 15:50:15

标签: excel excel-vba vba

我正在尝试将工作表从一个Excel工作簿复制并粘贴到另一个工作表。该工作表集成到该工作表的本地模型中。因此,我需要复制的工作表中的单元格引用在绝对意义上保持不变。

例如,"='Sheet1'C1"的单元格必须保留"='Sheet1'C1"而不是"='[OriginalWorkbook]Sheet1'C1"

现在,我在使用时遇到了意想不到的后果,

Sub TransferSheet(wka As Workbook, wkb As Workbook, WorksheetName As String)
    Dim ws1 As Worksheet
    wka.Activate
    Set ws1 = wka.Worksheets(WorksheetName)
    wkb.Activate
    ws1.Copy after:=wkb.Worksheets(Worksheets.Count)
End Sub

2 个答案:

答案 0 :(得分:1)

我认为这应该有效:

Sub TransferSheet(wka As Workbook, wkb As Workbook, WorksheetName As String)
    Dim ws1 As Worksheet
    wka.Activate
    Set ws1 = wka.Worksheets(WorksheetName)
    wkb.Activate
    ws1.Copy after:=wkb.Worksheets(Worksheets.Count)
    wkb.ChangeLink "wka.xls", "wkb.xls", xlExcelLinks
End Sub

编辑:此解决方案可用于更改宏按钮上的链接。

答案 1 :(得分:1)

我能够在超级用户上找到一个page,让我了解如何在VBA中解决这个问题。由于这是一个常见问题,人们已经使用了许多解决方案,例如将内容复制和粘贴到文本编辑器,然后返回到新工作表。另一种解决方案是使用查找和替换功能。

将此修改为VBA可以通过在复制后在工作表上进行查找和替换来解决问题。

Sub TransferSheet(wka As Workbook, wkb As Workbook, WorksheetName As String)
   Dim ws1 As Worksheet
   wka.Activate
   Set ws1 = wka.Worksheets(WorksheetName)
   wkb.Activate
   ws1.Copy after:=wkb.Worksheets(Worksheets.Count)
   wkb.ChangeLink "wka.xls", "wkb.xls", xlExcelLinks

   Dim sht As Worksheet
   Dim fnd As Variant
   Dim rplc As Variant

   fnd = "'[" & wka.Name & "]Summary'!"
   rplc = ""

   For Each sht In ActiveWorkbook.Worksheets
      sht.Cells.Replace what:=fnd, Replacement:=rplc, _
        LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, _
        SearchFormat:=False, ReplaceFormat:=False
   Next sht
End Sub