简体   繁体   English

使用Excel VBA复制工作表

[英]Copy sheet with excel vba

I am trying to copy one sheet from Workbook A to newly added Workbook B. The problem I have is that it does not keep the PageSetup. 我试图将一张纸从工作簿A复制到新添加的工作簿B。我遇到的问题是它没有保留PageSetup。 The new workbook with the copied sheet doesnt fit on one page as the original source does. 带有已复制工作表的新工作簿不能像原始来源那样放在一页上。 I have tried to research this but cant determine if I need to copy all the attributes in the PageSetup or if it should just work when copying the whole sheet. 我试图对此进行研究,但是无法确定是否需要复制PageSetup中的所有属性,或者在复制整个工作表时它是否应该工作。 This is my code so far: 到目前为止,这是我的代码:

     Public Sub makeCopies(ByVal seller As String)
        Dim thisWB As Workbook
        Dim newWB As Workbook
        Set thisWB = ActiveWorkbook

        Set newWB = Workbooks.Add
        On Error GoTo ErrorHandler:
        thisWB.Sheets(1).Copy Before:=newWB.Sheets(1)
        newWB.Activate

        newWB.SaveAs fileName:=seller & ".xlsx"
        newWB.Close
        thisWB.Activate
        Exit Sub

    ErrorHandler:
        MsgBox "Error" & Err.Number & Err.Description
        newWB.Close
    End Sub

It is a bit unclear as to exactly what Worksheet.PageSetup property or properties are not being carried across. 至于到底没有携带哪个 Worksheet.PageSetup属性,还是有点不清楚。 In the following procedure, modified slightly so that orphaned, blank worksheets are not included in the new workbook, the '× wide by × tall' property as well as 'rows to repeat at top' were carried across to the new worksheet/workbook faithfully. 在下面的过程中,进行了一些修改,以使孤立的空白工作表不包括在新工作簿中,“×宽×高”属性以及“在顶部重复的行”被忠实地传递到新工作表/工作簿中。

Sub main()
    makeCopies "makeCopies"
End Sub

Public Sub makeCopies(ByVal seller As String)
   Dim thisWB As Workbook
   Dim newWB As Workbook
   Set thisWB = ActiveWorkbook

   On Error GoTo ErrorHandler:
   thisWB.Sheets(1).Copy
   Set newWB = ActiveWorkbook

   newWB.SaveAs Filename:=Environ("TEMP") & Chr(92) & seller & ".xlsx"
   newWB.Close
   thisWB.Activate
   Exit Sub

ErrorHandler:
   MsgBox "Error" & Err.Number & Err.Description
   newWB.Close
End Sub

Copying a worksheet to 'no destination' creates a new workbook with that workbook holding the ActiveWorkbook property . 将工作表复制到“无目的地”会创建一个新工作簿,该工作簿具有ActiveWorkbook属性 The only worksheet will be a direct copy of the original which seems more desirable unless you need 1-3 blank worksheets in the new workbook for some reason. 唯一的工作表将是原始文件的直接副本,这似乎更可取,除非出于某种原因在新工作簿中需要1-3个空白工作表。

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

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