在另一个 Excel 文件中创建工作表的精确副本

问题描述 投票:0回答:1

我正在尝试在另一个文件中创建Excel工作表的精确副本。我尝试过以下三种方法

  1. 单元格引用 - 在其他文件中硬编码单元格引用,即
    $A$1
  2. VBA
  3. 使用
    PowerQuery
  4. 的数据连接

但是,每个都有其自身的局限性

  1. 单元格引用 - 如果我添加或删除列或行,引用将不起作用
  2. VBA
    - 这两个文件都需要打开,这在我们的情况下是不可能的
  3. Power Query - 它可以保持主动数据完整性,但在格式化时会完全失败,并且不会复制在
    comments
     中创建的 
    source file

我该怎么办? 我有一个截止日期,非常感谢任何指导。 预先感谢。

excel vba powerquery worksheet
1个回答
0
投票

使用 VBA,您可以将工作表从一个文件复制到另一个文件。 这对我来说是这样的 按 Alt+F11

Sub CopySheetToAnotherWorkbook()
    Dim sourceWorkbook As Workbook
    Dim targetWorkbook As Workbook
    Dim sourceSheet As Worksheet
    Dim targetSheet As Worksheet

    ' Update the paths and sheet names
    Dim sourceFilePath As String
    Dim targetFilePath As String
    Dim sourceSheetName As String
    Dim targetSheetName As String

    sourceFilePath = "C:\Path\To\SourceWorkbook.xlsx"
    targetFilePath = "C:\Path\To\TargetWorkbook.xlsx"
    sourceSheetName = "Sheet1"
    targetSheetName = "CopiedSheet"

    ' Open the source and target workbooks
    Set sourceWorkbook = Workbooks.Open(sourceFilePath)
    Set targetWorkbook = Workbooks.Open(targetFilePath)
    
    ' Set the source sheet
    Set sourceSheet = sourceWorkbook.Sheets(sourceSheetName)
    
    ' Check if target sheet already exists and delete it if it does
    On Error Resume Next
    Set targetSheet = targetWorkbook.Sheets(targetSheetName)
    If Not targetSheet Is Nothing Then
        Application.DisplayAlerts = False
        targetSheet.Delete
        Application.DisplayAlerts = True
    End If
    On Error GoTo 0
    
    ' Copy the sheet to the target workbook
    sourceSheet.Copy After:=targetWorkbook.Sheets(targetWorkbook.Sheets.Count)
    
    ' Rename the copied sheet
    Set targetSheet = targetWorkbook.Sheets(targetWorkbook.Sheets.Count)
    targetSheet.Name = targetSheetName
    
    ' Save and close the workbooks
    targetWorkbook.Save
    sourceWorkbook.Close False
    targetWorkbook.Close True
    
    MsgBox "Sheet copied successfully!"
End Sub

确保输入正确的路径和工作表名称

© www.soinside.com 2019 - 2024. All rights reserved.