简体   繁体   English

使用VBA复制整个工作表时如何复制值和格式

[英]How to copy values and formatting when copy entire sheet with VBA

I have the code below that works really well. 我下面的代码非常有效。

It copies the active worksheet and creates a new sheet with name based on a specific cell. 它复制活动的工作表并创建一个基于特定单元格名称的新工作表。

Can I modify this to not include formulas when copied? 复制后可以修改为不包含公式吗? I only want Values and Formatting, so the new sheet is a static snapshot. 我只需要“值和格式”,因此新表是静态快照。

Sub Copyrenameworksheet()
Dim ws As Worksheet
Set wh = Worksheets(ActiveSheet.Name)
ActiveSheet.Copy After:=Worksheets(ActiveSheet.Name)
If wh.Range("C2").Value <> "" Then
ActiveSheet.Name = wh.Range("C2").Value
End If
wh.Activate
End Sub

How about the following as a general method to make a static copy of a worksheet: 下面是制作工作表静态副本的一般方法:

Dim sht1 As Worksheet 'worksheet to copy from
Dim sht2 As Worksheet 'worksheet to paste to
Set sht1 = ThisWorkbook.Worksheets("Name of the Worksheet to copy from")
sht1.Cells.Copy 'Copy everything in the worksheet
Set sht2 = ThisWorkbook.Worksheets.Add 'create new blank worksheet
sht2.Cells.PasteSpecial xlPasteValues 'first paste values
sht2.Cells.PasteSpecial xlPasteFormats ' then paste formats
sht2.Name="Something" 'give a name to your new worksheet

Also please avoid using ActiveSheet and use explicit references to your worksheets instead. 另外,请避免使用ActiveSheet,而应使用对工作表的显式引用。

I modified your code slightly to use variables for your original sheet and your copied sheet. 我对代码进行了一些修改,以将变量用于原始工作表和复制的工作表。 I use .Value2 = .Value2 to remove formulas. 我使用.Value2 = .Value2删除公式。 Note that this will run into an error if you try to create multiple sheets using the same name in C2 . 请注意,如果您尝试在C2使用相同的名称创建多个图纸,则会遇到错误。

Sub Copyrenameworksheet()
Dim wsOrig As Worksheet, wsNew As Worksheet

Set wsOrig = Worksheets(ActiveSheet.Name)
wsOrig.Copy , wsOrig
Set wsNew = Worksheets(wsOrig.Index + 1)

If wsOrig.Range("C2").Value <> "" Then
    wsNew.Name = wsOrig.Range("C2").Value
End If

wsNew.UsedRange.Value2 = wsNew.UsedRange.Value2

wsOrig.Activate

End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM