在Excel 2010中将整个工作表复制到新工作表

28
我发现了一些类似的问题,它们处理的是将整个工作簿中的一个工作表复制并粘贴到另一个工作簿中,但我只想简单地将整个工作表复制并粘贴到一个新的工作表中——在同一个工作簿中。我正在将一个2003 .xls文件转换为2010 .xlsm,旧方法用于在工作表之间复制和粘贴时无法保留正确的行高度。我的初始解决方法是循环遍历每一行,并从我要复制的工作表中获取行高度,然后循环遍历并在我要粘贴到的工作表中插入这些行高度值,但这种方法的问题是该工作表包含按钮,这些按钮会生成新的行,从而改变行编号,而且该工作表的格式是不能所有行都是同一宽度的。我真正想做的是只需简单地将整个工作表复制并粘贴。下面是来自2003版本的代码:
ThisWorkbook.Worksheets("Master").Cells.Copy
newWorksheet.Paste

我很惊讶转换为 .xlsm 现在导致它无法正常工作。如果有任何建议或想法将不胜感激。

6个回答

40

以下的操作更简单,可以运行一个完全相同的副本将其放置在最后一个工作表中。

Sub Test()
Dim ws1 As Worksheet
Set ws1 = ThisWorkbook.Worksheets("Master")
ws1.Copy ThisWorkbook.Sheets(Sheets.Count)
End Sub

19
ThisWorkbook.Worksheets("Master").Sheet1.Cells.Copy _
    Destination:=newWorksheet.Cells

以上代码将复制单元格。如果您真的想要复制整个工作表,那么我建议使用@brettdj的答案


7
建议复制使用范围,而不是所有单元格。 - brettdj

8
' Assume that the code name the worksheet is Sheet1

' Copy the sheet using code name and put in the end.
' Note: Using the code name lets the user rename the worksheet without breaking the VBA code
Sheet1.Copy After:=Sheets(Sheets.Count)

' Rename the copied sheet keeping the same name and appending a string " copied"
ActiveSheet.Name = Sheet1.Name & " copied"

2

我非常喜欢@brettdj的代码,但是当我添加了额外的代码来编辑副本时,它覆盖了我的原始表格。我调整了他的答案,以便进一步指向ws1的代码将影响新表格而不是原始表格。

Sub Test()
    Dim ws1 as Worksheet
    ThisWorkbook.Worksheets("Master").Copy
    Set ws1 = ThisWorkbook.Worksheets("Master (2)")
End Sub

1
'Make the excel file that runs the software the active workbook
ThisWorkbook.Activate

'The first sheet used as a temporary place to hold the data 
ThisWorkbook.Worksheets(1).Cells.Copy

'Create a new Excel workbook
Dim NewCaseFile As Workbook
Dim strFileName As String

Set NewCaseFile = Workbooks.Add
With NewCaseFile
    Sheets(1).Select
    Cells(1, 1).Select
End With

ActiveSheet.Paste

1
顺便提一下,您不需要选择新工作簿和工作表进行粘贴,只需使用 NewCaseFile.Worksheets(1).Paste 即可。 - Olle Sjögren

0

如果有人像我一样拥有一个估算工作簿,其中有一定数量的可见价格表、一个汇总表和大量包含敏感数据的隐藏和“受保护”工作表,但可能需要创建额外的可见工作表以得出适当的价格,那么我有一种以上回答的变体,它基于受保护的隐藏“主”工作表创建所述可见工作表。我已经使用@/jean-fran%c3%a7ois-corbett和@thanos-a提供的代码与简单的VBA相结合,如下所示。

子sbInsertWorksheetAfter()

    'This adds a new visible worksheet after the last visible worksheet

    ThisWorkbook.Sheets.Add After:=Worksheets(Worksheets.Count)

    'This copies the content of the HIDDEN "Master" worksheet to the new VISIBLE ActiveSheet just created

    ThisWorkbook.Sheets("Master").Cells.Copy _
        Destination:=ActiveSheet.Cells

    'This gives the the new ActiveSheet a default name

    With ActiveSheet
        .Name = Sheet12.Name & " copied"
    End With

    'This changes the name of the ActiveSheet to the user's preference

    Dim sheetname As String

    With ActiveSheet
        sheetname = InputBox("Enter name of this Worksheet")
        .Name = sheetname
    End With

结束子程序


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接